add core api
This commit is contained in:
14
src/common/services/file-storage/abstract.file-storage.ts
Normal file
14
src/common/services/file-storage/abstract.file-storage.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
export type FileResult = {
|
||||
name: string;
|
||||
mimeType: string;
|
||||
extension: string;
|
||||
buffer: Buffer;
|
||||
};
|
||||
|
||||
export abstract class AbstractFileStorage {
|
||||
public abstract storeFile(buffer: Buffer, name?: string): Promise<FileResult>;
|
||||
|
||||
public abstract retrieveFile(name: string): Promise<FileResult>;
|
||||
|
||||
public abstract removeFile(name: string): Promise<void>;
|
||||
}
|
||||
59
src/common/services/file-storage/local.file-storage.ts
Normal file
59
src/common/services/file-storage/local.file-storage.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { InvalidFileBufferError } from "@/common/errors/invalid-file-buffer.error";
|
||||
import {
|
||||
AbstractFileStorage,
|
||||
type FileResult,
|
||||
} from "@/common/services/file-storage/abstract.file-storage";
|
||||
import { fileTypeFromBuffer } from "file-type";
|
||||
import { join } from "node:path";
|
||||
|
||||
const STORAGE_DIRECTORY = join(process.cwd(), "storage");
|
||||
|
||||
export class LocalFileStorage extends AbstractFileStorage {
|
||||
public constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
public async storeFile(buffer: Buffer, name?: string): Promise<FileResult> {
|
||||
const fileType = await fileTypeFromBuffer(buffer);
|
||||
if (!fileType) {
|
||||
throw new InvalidFileBufferError(
|
||||
buffer,
|
||||
"Unable to determine file type from buffer.",
|
||||
);
|
||||
}
|
||||
|
||||
const fileName = name ?? `${Date.now()}.${fileType.ext}`;
|
||||
|
||||
const filePath = join(STORAGE_DIRECTORY, fileName);
|
||||
|
||||
await Bun.write(filePath, buffer, { createPath: true });
|
||||
|
||||
return {
|
||||
name: fileName,
|
||||
buffer,
|
||||
mimeType: fileType.mime,
|
||||
extension: fileType.ext,
|
||||
};
|
||||
}
|
||||
|
||||
public async retrieveFile(name: string): Promise<FileResult> {
|
||||
const filePath = join(STORAGE_DIRECTORY, name);
|
||||
|
||||
const file = Bun.file(filePath);
|
||||
|
||||
const fileName = file.name ?? name;
|
||||
|
||||
return {
|
||||
name: fileName,
|
||||
buffer: Buffer.from(await file.arrayBuffer()),
|
||||
mimeType: file.type,
|
||||
extension: fileName.split(".").pop() ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
public async removeFile(name: string): Promise<void> {
|
||||
const filePath = join(STORAGE_DIRECTORY, name);
|
||||
|
||||
await Bun.file(filePath).delete();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user