@paroicms/server
Version:
The ParoiCMS server
83 lines • 3.12 kB
JavaScript
import { getNodeTypeByName } from "@paroicms/internal-anywhere-lib";
import { ApiError } from "@paroicms/public-server-lib";
import { type } from "arktype";
import { createNode } from "../../connector/db-init/init-node-queries.js";
import { autoCreatePartFieldParts } from "../part/auto-create-part-field-parts.js";
import { createPartNode } from "../part/part-node.queries.js";
export async function createSinglePartFieldNode(siteContext, options) {
const { nodeId, fieldName, language } = options;
const { cn, siteSchema } = siteContext;
const typeName = await getTypeNameOf(siteContext, nodeId);
const nodeType = getNodeTypeByName(siteSchema, typeName);
const field = nodeType.fields?.find((f) => f.name === fieldName && f.storedAs === "partField");
if (!field)
throw new ApiError(`field '${fieldName}' is not a partField on type '${typeName}'`, 400);
await assertPartFieldNodeDoesNotExist(cn, nodeId, fieldName);
const documentNodeId = await resolveDocumentNodeId(cn, nodeId);
const newNodeId = await cn.transaction(async (tx) => {
const node = await createNode(siteSchema, tx, {
parentId: nodeId,
typeName: field.partType,
});
await createPartNode(tx, {
nodeId: node.id,
listName: `_pf:${fieldName}`,
documentNodeId,
isOrdered: false,
lastOrderNum: undefined,
});
await tx("PaLNode").insert({
language,
nodeId: node.id,
ready: true,
updatedAt: tx.raw("current_timestamp"),
});
await autoCreatePartFieldParts(siteSchema, {
parentNodeId: node.id,
typeName: field.partType,
language,
documentNodeId,
tx,
});
return node.id;
});
return newNodeId;
}
async function getTypeNameOf(siteContext, nodeId) {
const row = await siteContext
.cn("PaNode as n")
.select("n.typeName")
.where("n.id", nodeId)
.first();
if (!row)
throw new ApiError(`cannot find node '${nodeId}'`, 404);
return TypeNameRowAT.assert(row).typeName;
}
const TypeNameRowAT = type({
typeName: "string",
"+": "reject",
});
async function assertPartFieldNodeDoesNotExist(cn, nodeId, fieldName) {
const existing = await cn("PaPartNode as p")
.select("p.nodeId")
.innerJoin("PaNode as n", "n.id", "p.nodeId")
.where("n.parentId", nodeId)
.andWhere("p.listName", `_pf:${fieldName}`)
.first();
if (existing)
throw new ApiError(`part field node for '${fieldName}' already exists`, 409);
}
const DocumentNodeIdRowAT = type({
documentNodeId: "number",
"+": "reject",
}).pipe((r) => String(r.documentNodeId));
async function resolveDocumentNodeId(cn, nodeId) {
const row = await cn("PaPartNode as p")
.select("p.documentNodeId")
.where("p.nodeId", nodeId)
.first();
if (!row)
return nodeId;
return DocumentNodeIdRowAT.assert(row);
}
//# sourceMappingURL=create-part-field-node.js.map