@paroicms/server
Version:
The ParoiCMS server
55 lines • 2.09 kB
JavaScript
import { getNodeTypeByName } from "@paroicms/internal-anywhere-lib";
import { ApiError } from "@paroicms/public-server-lib";
import { type } from "arktype";
import { makeDefaultThumbAvailableForAdminUi } from "../../common/medias/media-lib.js";
import { removeExtensionFromFileName } from "../../helpers/utils-helper.js";
import { getTypeNameOf } from "../node/node.queries.js";
import { addMediaToNode } from "./add-media-to-node.js";
const UploadBodyAT = type({
nodeId: "string",
handle: "string",
"attachedData?": "string|undefined",
replace: `"0"|"1"`,
"+": "reject",
}).pipe((d) => ({
...d,
attachedData: d.attachedData ? JSON.parse(d.attachedData) : undefined,
replace: d.replace === "1",
}));
export async function uploadMediaController(siteContext, httpContext) {
const { req } = httpContext;
const file = req.file;
const body = req.body;
if (!file)
throw new ApiError("missing file", 400);
const { nodeId, handle, attachedData, replace } = UploadBodyAT.assert(body);
const typeName = await getTypeNameOf(siteContext, nodeId);
const nodeType = getNodeTypeByName(siteContext.siteSchema, typeName);
const { buffer: binaryFile, mimetype: mediaType } = file;
const originalName = removeExtensionFromFileName(Buffer.from(file.originalname, "latin1").toString("utf8"));
const weightB = binaryFile.byteLength;
if (file.size !== weightB) {
throw new ApiError(`file size mismatch (should be ${weightB}, actual ${file.size})`, 400);
}
const source = await addMediaToNode(siteContext, { binaryFile, originalName, weightB, mediaType }, {
nodeId,
nodeType,
handle,
attachedData,
replace,
});
if (source.kind === "image") {
return {
kind: "image",
source,
thumb: await makeDefaultThumbAvailableForAdminUi(siteContext, source, {
absoluteUrl: true,
}),
};
}
return {
kind: "file",
source,
};
}
//# sourceMappingURL=media-upload.controller.js.map