@paroicms/server
Version:
The ParoiCMS server
43 lines • 1.56 kB
JavaScript
import { getNodeTypeByName } from "@paroicms/internal-anywhere-lib";
import mime from "mime";
import { readFile } from "node:fs/promises";
import { basename } from "node:path";
import { addMediaToNode } from "../admin-backend/media/add-media-to-node.js";
import { getTypeNameOf } from "../admin-backend/node/node.queries.js";
import { getNodeIdFromHandle } from "../common/media-handles.helpers.js";
export async function setMediaProgrammaticApi(siteContext, mediaInput) {
const { handle, filePath, attachedData, replace } = mediaInput;
const nodeId = getNodeIdFromHandle(siteContext, handle);
const typeName = await getTypeNameOf(siteContext, nodeId);
const nodeType = getNodeTypeByName(siteContext.siteSchema, typeName);
return await addMediaFile(siteContext, {
nodeId,
nodeType,
handle,
path: filePath,
attachedData,
replace,
});
}
async function addMediaFile(siteContext, options) {
const { nodeId, nodeType, path, handle, attachedData, replace } = options;
const filename = basename(path);
const binaryFile = await readFile(path);
const mediaType = mime.getType(path);
if (!mediaType) {
throw new Error(`Cannot determine media type of "${path}"`);
}
return await addMediaToNode(siteContext, {
binaryFile,
originalName: filename,
weightB: binaryFile.byteLength,
mediaType,
}, {
nodeId,
nodeType,
handle,
attachedData,
replace,
});
}
//# sourceMappingURL=media-api.js.map