aboutsummaryrefslogtreecommitdiffstats
path: root/lib/upload.ts
blob: bc358ede3aebadb9b5a8bb1bdcb1988075579c8a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { fileTypeFromBuffer } from "file-type";
import { writeFileSync } from "fs";
import { bail, fail } from "$lib/utils";
import { createHash } from "crypto";
import { err } from "$lib/logging";

const sharp = require("sharp");

export default async (req, res) => {
  try {
    const {
      params: { type },
    } = req;

    const data = await req.file();
    let buf = await data.toBuffer();

    const [format, ext] = (await fileTypeFromBuffer(buf)).mime.split("/");

    if (format !== "image" && !["jpg", "jpeg", "png"].includes(ext))
      fail("unsupported file type");

    const w = type === "banner" ? 1920 : 240;
    buf = await sharp(buf, { failOnError: false })
      .rotate()
      .resize(w)
      .webp()
      .toBuffer();

    const hash = createHash("sha256").update(buf).digest("hex");

    const filePath = `/home/bun/app/data/uploads/${hash}.webp`;
    writeFileSync(filePath, buf);

    res.send({ hash });
  } catch (e) {
    err("problem uploading", e.message);
    bail(res, e.message);
  }
};