Skip to content

Commit

Permalink
Split route
Browse files Browse the repository at this point in the history
  • Loading branch information
FoundTheWOUT committed Nov 23, 2024
1 parent b25627e commit 11391f1
Show file tree
Hide file tree
Showing 5 changed files with 4,691 additions and 3,702 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
},
"dependencies": {
"nanoid": "^4.0.1",
"typescript": "4.9.5"
"typescript": "5.4.5"
},
"devDependencies": {
"@types/node": "18.14.1"
Expand Down
7 changes: 3 additions & 4 deletions packages/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ import morgan from "morgan";
import cors from "cors";
import { ENABLE_HTTPS, ENABLE_OSS, isProd, VERSION } from "./const";
import { log } from "./utils";
import { musicRoute } from "./routes/music";
import { getAppContext } from "./ctx";
import { musicRoute, uploadRoute } from "./routes";
import https from "https";
import { readFileSync, createWriteStream } from "fs";
import path from "path";
Expand All @@ -28,7 +27,6 @@ const accessLogStream = createWriteStream(

async function bootstrap() {
try {
const { ossClient } = await getAppContext();
const app = express();

app
Expand All @@ -52,7 +50,8 @@ async function bootstrap() {
)
)
.use("/uploads", express.static("uploads"))
.use(await musicRoute());
.use(await musicRoute())
.use(await uploadRoute());

app.get("/ping", (req, rep) => {
return rep.end("pong");
Expand Down
2 changes: 2 additions & 0 deletions packages/server/src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./music";
export * from "./upload";
138 changes: 138 additions & 0 deletions packages/server/src/routes/upload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import express, { Router } from "express";
import { auth } from "middleware/authentication";
import { getAppContext } from "@/ctx";
import sharp from "sharp";
import multer from "multer";
import { ENABLE_OSS } from "@/const";
import OSS from "ali-oss";
import { log } from "@/utils";
import { parseFile, parseBuffer } from "music-metadata";

const upload = multer({
storage: ENABLE_OSS
? multer.memoryStorage()
: multer.diskStorage({
destination: "uploads/",
}),
});

const webpUpload = multer({
storage: ENABLE_OSS
? multer.memoryStorage()
: multer.diskStorage({
destination: "uploads/",
filename: function (req, file, cb) {
const uniqueSuffix =
Date.now() + "-" + Math.round(Math.random() * 1e9);
cb(null, `local-${uniqueSuffix}.webp`);
},
}),
});

const sharpImageToWebp = async (buf: Buffer) => {
const output = await sharp(buf)
.resize(200)
.webp({ lossless: true })
.toBuffer();
return output;
};

// return the Map<nanoid(from front_end),new_file_name(from multer)>
// the new_file_name will store into db. And frontend will concat the value with Static path later.
const ossPut = async (
client: OSS,
files: Express.Multer.File[],
filenameFormatter?: (name: string) => string
): Promise<Record<string, string>> => {
try {
const entry = await Promise.all(
files.map(async (file) => {
const id = file.originalname;
const name = ENABLE_OSS
? filenameFormatter
? filenameFormatter(id)
: id
: file.filename;

if (ENABLE_OSS) {
await client.put(name, file.buffer);
}
return [id, name];
})
);
return Object.fromEntries(entry);
} catch (error) {
throw error;
}
};

export async function uploadRoute(): Promise<Router> {
const { ossClient } = await getAppContext();

const route = express.Router();

route.post(
"/upload/image",
auth({ allowGuest: true }),
webpUpload.array("file", 20),
async function (req, rep) {
if (!Array.isArray(req.files)) {
return rep.status(400).send("files is not array.");
}
try {
// sharp image
const files: Express.Multer.File[] = await Promise.all(
req.files.map(async (file) => {
return {
...file,
buffer: file.buffer && (await sharpImageToWebp(file.buffer)),
} as Express.Multer.File;
})
);
const fileMap = await ossPut(
ossClient,
files,
(name) => `${name}.webp`
);
return rep.send(fileMap);
} catch (error) {
log(error);
return rep.status(500).send(error);
}
}
);

route.post(
"/upload/song",
auth({ allowGuest: true }),
upload.array("file", 20),
async function (req, rep) {
// TODO: check music length
if (!Array.isArray(req.files)) {
return rep.status(400).send("files is not array.");
}
try {
for (const file of req.files) {
const meta = file.buffer
? await parseBuffer(file.buffer)
: await parseFile(`uploads/${file.filename}`);
if (meta.format.duration > 18) {
return rep.status(400).send("Music too long.");
}
}
} catch (error) {
log(error);
return rep.status(400).send((error as Error).message);
}
try {
const fileMap = await ossPut(ossClient, req.files);
return rep.send(fileMap);
} catch (error) {
log(error);
return rep.status(400).send(`Put Music Failed`);
}
}
);

return route;
}
Loading

0 comments on commit 11391f1

Please sign in to comment.