@npio/internals
Version:
A free visual website editor, powered with your own SolidJS components.
150 lines (134 loc) • 3.54 kB
text/typescript
import { Element } from "../../../types";
import { createIdMap } from "../../normalization";
import { ROOT_ELEMENT_ID } from "../../string";
import { blueprintPaths } from "../page";
import { useDatabase } from "../prisma";
export const getRevision = async (id: string, dates = false) => {
const db = useDatabase();
const result = await db.nitroPageRevision.findUnique({
where: {
id,
},
select: {
id: true,
pageId: true,
title: true,
urlPath: true,
publishedPage: {
omit: {
createdAt: !dates,
updatedAt: !dates,
},
},
updatedAt: dates,
createdAt: dates,
elements: {
include: {
slots: {
include: {
elements: {
select: { id: true },
orderBy: {
position: "asc",
},
},
},
},
},
},
rootSlots: {
omit: {
createdAt: !dates,
updatedAt: !dates,
},
include: {
elements: {
select: { id: true },
orderBy: {
position: "asc",
},
},
},
},
},
});
if (!result) return;
const slots = {} as Record<string, ReturnType<typeof normalizeSlot>>;
const normalizeSlot = (slot: (typeof result)["elements"][0]["slots"][0]) => {
const { updatedAt, createdAt, ...rest } = slot;
return {
...rest,
parentElementId: slot.parentElementId!,
elements: slot.elements.map((e) => e.id),
};
};
const blueprintIds: Record<string, boolean> = {};
const blueprintFiles: Record<string, boolean> = {};
const elements = createIdMap(result.elements, (element) => {
const elementSlots: Record<string, string> = {};
for (const slot of element.slots) {
slots[slot.id] = normalizeSlot(slot);
elementSlots[slot.key] = slot.id;
}
if (element.blueprintId && blueprintPaths[element.blueprintId]) {
blueprintIds[element.blueprintId] = true;
blueprintFiles[blueprintPaths[element.blueprintId]] = true;
}
const { updatedAt, createdAt, ...rest } = element;
const result: Element = {
...rest,
data: JSON.parse(element.data),
slots: elementSlots,
};
return result;
});
const rootSlots = {} as Record<string, string>;
for (const slot of result.rootSlots) {
rootSlots[slot.key] = slot.id;
slots[slot.id] = normalizeSlot(slot);
slots[slot.id].parentElementId = ROOT_ELEMENT_ID;
}
elements[ROOT_ELEMENT_ID] = {
id: ROOT_ELEMENT_ID,
blueprintId: ROOT_ELEMENT_ID,
data: {},
slots: rootSlots,
} as (typeof elements)[0];
return {
...result,
blueprintIds: Object.keys(blueprintIds),
blueprintFiles: Object.keys(blueprintFiles),
elements,
slots,
};
};
export type PageRevision = NonNullable<Awaited<ReturnType<typeof getRevision>>>;
export const getPublishedRevision = async function ({
projectId,
pageId,
urlPath,
}: {
projectId?: string;
pageId?: string;
urlPath?: string;
}) {
const prisma = useDatabase();
const revision = await prisma.nitroPageRevision.findFirst({
where: {
publishedPage: { id: { not: undefined } },
urlPath: urlPath,
page: {
id: pageId,
projectId,
type: {
equals: null,
},
},
},
select: {
id: true,
},
});
if (!revision) return;
return await getRevision(revision.id);
};