Add batch image jobs runtime
This commit is contained in:
21
src/image.ts
21
src/image.ts
@@ -1,7 +1,16 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
const IMAGES_DIR = "images";
|
||||
const OUTPUT_DIR = "output";
|
||||
|
||||
function sanitizeFileNamePart(value: string): string {
|
||||
return value
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 60);
|
||||
}
|
||||
|
||||
function mediaTypeToExtension(mediaType: string): string {
|
||||
switch (mediaType) {
|
||||
@@ -18,19 +27,21 @@ function mediaTypeToExtension(mediaType: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
function createTimestampFileName(mediaType: string): string {
|
||||
function createTimestampFileName(mediaType: string, name?: string): string {
|
||||
const extension = mediaTypeToExtension(mediaType);
|
||||
const timestamp = new Date().toISOString().replace(/[.:]/g, "-");
|
||||
return `${timestamp}.${extension}`;
|
||||
const prefix = name ? `${sanitizeFileNamePart(name)}-` : "";
|
||||
return `${prefix}${timestamp}.${extension}`;
|
||||
}
|
||||
|
||||
export async function saveImage(
|
||||
bytes: Uint8Array,
|
||||
mediaType: string,
|
||||
name?: string,
|
||||
): Promise<string> {
|
||||
await mkdir(IMAGES_DIR, { recursive: true });
|
||||
await mkdir(OUTPUT_DIR, { recursive: true });
|
||||
|
||||
const filePath = join(IMAGES_DIR, createTimestampFileName(mediaType));
|
||||
const filePath = join(OUTPUT_DIR, createTimestampFileName(mediaType, name));
|
||||
await writeFile(filePath, bytes);
|
||||
|
||||
return filePath;
|
||||
|
||||
Reference in New Issue
Block a user