57 lines
1.4 KiB
TypeScript
57 lines
1.4 KiB
TypeScript
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
|
|
const imageDir = join(
|
|
/* turbopackIgnore: true */ process.cwd(),
|
|
"public",
|
|
"generated",
|
|
);
|
|
|
|
export type PersistedImageFile = {
|
|
fileName: string;
|
|
filePath: string;
|
|
imageUrl: string;
|
|
};
|
|
|
|
export function getImageDir() {
|
|
if (!existsSync(imageDir)) {
|
|
mkdirSync(imageDir, { recursive: true });
|
|
}
|
|
|
|
return imageDir;
|
|
}
|
|
|
|
export function persistBase64Image(
|
|
id: string,
|
|
extension: string,
|
|
base64: string,
|
|
): PersistedImageFile {
|
|
const normalizedExtension = extension === "jpeg" ? "jpg" : extension;
|
|
const fileName = `${id}.${normalizedExtension}`;
|
|
const filePath = join(getImageDir(), fileName);
|
|
const imageUrl = `/generated/${fileName}`;
|
|
writeFileSync(filePath, Buffer.from(base64, "base64"));
|
|
|
|
return { fileName, filePath, imageUrl };
|
|
}
|
|
|
|
export function persistUploadedImageFile(
|
|
id: string,
|
|
filename: string,
|
|
buffer: Buffer,
|
|
): PersistedImageFile {
|
|
const extension = getExtensionFromFilename(filename);
|
|
const fileName = `${id}.${extension}`;
|
|
const filePath = join(getImageDir(), fileName);
|
|
const imageUrl = `/generated/${fileName}`;
|
|
writeFileSync(filePath, buffer);
|
|
|
|
return { fileName, filePath, imageUrl };
|
|
}
|
|
|
|
function getExtensionFromFilename(filename: string) {
|
|
const parts = filename.split(".");
|
|
const extension = parts.at(-1)?.toLowerCase();
|
|
return extension && extension.length <= 5 ? extension : "png";
|
|
}
|