next/server/api/upload/avatar.post.ts

37 lines
755 B
TypeScript
Raw Normal View History

2023-10-03 00:58:52 -04:00
import { v4 } from "uuid";
import { resolve } from "path";
import { isLoggedIn } from "@server/middlewareButNotReally";
import sharp from "sharp";
import { User } from "@models/user";
2023-10-03 00:58:52 -04:00
export default eventHandler(async (ev) => {
isLoggedIn(ev);
let mpd = await readMultipartFormData(ev);
if (!mpd) {
throw createError({
statusCode: 400,
});
}
let si = sharp(mpd[0].data!);
let nn = v4();
await si
.resize({
height: 500,
width: 500,
fit: "outside",
background: { r: 0, g: 0, b: 0, alpha: 0 },
})
.toFormat("png")
.toFile(resolve(`public/avatars/${nn}.png`));
await User.findByIdAndUpdate(ev.context.currentUser!._id, {
$set: {
"profile.avatar": nn,
},
});
2023-10-03 00:58:52 -04:00
return {
success: true,
file: `${nn}.png`,
};
});