add:utils:file:store | create utility for store file in system
This commit is contained in:
26
src/helpers/files/saveFile/index.ts
Normal file
26
src/helpers/files/saveFile/index.ts
Normal file
@ -0,0 +1,26 @@
|
||||
import { mkdir, writeFile } from "fs/promises";
|
||||
import path from "path";
|
||||
import crypto from "crypto";
|
||||
import mime from "mime-types";
|
||||
|
||||
interface SaveFileOptions {
|
||||
folder: string;
|
||||
prefix?: string;
|
||||
}
|
||||
|
||||
export const saveFile = async (
|
||||
file: File,
|
||||
{ folder, prefix }: SaveFileOptions
|
||||
): Promise<string> => {
|
||||
const ext = mime.extension(file.type) || "bin";
|
||||
const uniqueName = `${prefix ?? ""}${crypto.randomUUID()}.${ext}`;
|
||||
|
||||
const relativeFolder = path.join("uploads", folder);
|
||||
const relativePath = path.join(relativeFolder, uniqueName);
|
||||
const absolutePath = path.join(process.cwd(), relativePath);
|
||||
|
||||
await mkdir(path.dirname(absolutePath), { recursive: true });
|
||||
await writeFile(absolutePath, Buffer.from(await file.arrayBuffer()));
|
||||
|
||||
return relativePath;
|
||||
};
|
||||
17
src/helpers/files/saveFile/modules/saveAvatar.ts
Normal file
17
src/helpers/files/saveFile/modules/saveAvatar.ts
Normal file
@ -0,0 +1,17 @@
|
||||
import { saveFile } from "..";
|
||||
import { AppError } from "../../../error/instances/app";
|
||||
|
||||
export const saveAvatar = async (file: File): Promise<string> => {
|
||||
const allowedTypes = ["image/png", "image/jpeg", "image/webp"];
|
||||
if (!allowedTypes.includes(file.type)) {
|
||||
throw new AppError(
|
||||
415,
|
||||
"Unsupported Media Type. File must be in .jpg, .png, or .webp format"
|
||||
);
|
||||
}
|
||||
|
||||
return await saveFile(file, {
|
||||
folder: "avatar",
|
||||
prefix: "usr-",
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user