import { ExpressGetServer, createFunction, } from "@idot-digital/function-generator"; import { DEFAULT_AUTH_LAYER, app } from "../app.js"; import { ctx } from "../context.js"; //# DATA TYPE import z from "zod"; import { DATA_FROM_ZOD } from "@idot-digital/function-generator/dist/index.client.js"; import { url } from "../config.client.js"; import { Link } from "../types.js"; const FUNC_ZOD = { REQ: z.object({}).strict(), OPT: z.object({ uid: z.string() }), RES: z.discriminatedUnion("code", [ z.object({ code: z.literal(200), data: z.array( Link.omit({ owner: true }) .extend({ owner: z.boolean() }) .extend({ shared: z.array(z.string()) }) ), }), z.object({ code: z.literal(500), data: z.literal("Internal server error"), }), ]), }; export type DATA = DATA_FROM_ZOD; const CLIENT_SETTINGS = { path: "/getLinks", url, }; //# export const getLinks = ctx .createFunction( FUNC_ZOD, async ({}, { uid }, { auth0, sql }): Promise => { const roles = await auth0.users.getRoles({ id: uid }); if (roles.status !== 200) { return { code: 500, data: "Internal server error", }; } const groupIdArray = roles.data.map((role) => role.id); const sharedLink = sql .prepare( `SELECT link_id FROM link_sharing WHERE group_id IN (${groupIdArray .map(() => "?") .join(", ")});` ) .all(...groupIdArray) as { link_id: number }[]; const sharedLinkArray = sharedLink.map((link) => link.link_id); const result = sql .prepare( `SELECT DISTINCT * FROM links WHERE owner = ? OR id IN (${sharedLinkArray .map(() => "?") .join(", ")});` ) .all(uid, ...sharedLinkArray) as z.infer[]; const resultArrayLinkId = result.map((link) => link.id); const groupsListofLink = sql .prepare( `SELECT group_id, link_id FROM link_sharing WHERE link_id IN (${resultArrayLinkId .map(() => "?") .join(", ")});` ) .all(...resultArrayLinkId) as { link_id: string; group_id: string }[]; const mappedResult = result.map((link: any) => { link.active = link.active === 1; link.owner = link.owner === uid; link.shared = groupsListofLink .filter((group) => group.link_id === link.id) .map((group) => group.group_id); return link as Omit, "owner"> & { owner: boolean; shared: string[]; }; }); return { code: 200, data: mappedResult, }; } ) .addLayer(DEFAULT_AUTH_LAYER) .addTransport( ExpressGetServer.create({ app, path: CLIENT_SETTINGS.path, }) );