@paroicms/server
Version:
The ParoiCMS server
71 lines • 2.81 kB
JavaScript
import { getNodeTypeByName } from "@paroicms/internal-anywhere-lib";
import { ApiError } from "@paroicms/public-server-lib";
import { type } from "arktype";
import { getNodeIdFromHandle } from "../../common/media-handles.helpers.js";
import { makeDefaultThumbAvailableForAdminUi } from "../../common/medias/media-lib.js";
import { removeExtensionFromFileName } from "../../helpers/utils-helper.js";
import { permissionGuard } from "../auth/authorization.helper.js";
import { recordEvent } from "../event-log/event-log.service.js";
import { getTypeNameOf } from "../node/node.queries.js";
import { addMediaToNode } from "./add-media-to-node.js";
const UploadBodyAT = type({
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 authorizedAccount = await permissionGuard(siteContext, httpContext, "document.edit");
const { req } = httpContext;
const file = req.file;
const body = req.body;
if (!file)
throw new ApiError("missing file", 400);
const { handle, attachedData, replace } = UploadBodyAT.assert(body);
const nodeId = getNodeIdFromHandle(siteContext, handle);
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,
});
recordEvent(siteContext, {
eventType: "media.create",
actorId: authorizedAccount.accountId,
targetType: "media",
targetId: source.mediaId,
eventData: {
mediaId: source.mediaId,
filename: source.originalName ?? originalName,
mimeType: source.mediaType,
sizeBytes: weightB,
},
});
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