All files / blong-gogo/src/adapter/schema schemaCrudBind.ts

0% Statements 0/174
0% Branches 0/1
0% Functions 0/1
0% Lines 0/174

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175                                                                                                                                                                                                                                                                                                                                                             
import {library} from '@feasibleone/blong';
import {Type, type TFunction, type TObject, type TSchema} from 'typebox';

interface IColumnSchema {
    type?: string;
}

function capitalize(str: string): string {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

export default library(
    ({config}) =>
        async function schemaCrudBind(
            subject: string,
            object: string,
            schema: TObject,
            existingHandlers: string[] = [],
        ): Promise<{
            handlers: Record<string, (params: Record<string, unknown>) => Promise<unknown>>;
            schemas: Record<string, TFunction>;
        }> {
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            const knex = (config as Record<string, any>)?.context?.queryBuilder;
            if (!knex) throw new Error('Knex queryBuilder not available in adapter context');

            const existing = new Set(existingHandlers);
            const tableName = object;
            const objectId = `${object}Id`;
            const objectCapitalized = capitalize(object);

            const handlers: Record<
                string,
                (params: Record<string, unknown>) => Promise<unknown>
            > = {};
            const schemas: Record<string, TFunction> = {};

            const required = new Set(schema.required ?? []);
            const idSchema = (schema.properties[objectId] as TSchema) ?? Type.String();

            const entitySchema = Type.Object(
                Object.fromEntries(
                    Object.entries(schema.properties).map(([k, v]) => [k, v as TSchema]),
                ),
            );

            const allOptionalProps: Record<string, TSchema> = {};
            for (const [name, prop] of Object.entries(schema.properties)) {
                allOptionalProps[name] = Type.Optional(prop as TSchema);
            }

            const addProps: Record<string, TSchema> = {};
            for (const [name, prop] of Object.entries(schema.properties)) {
                if (name === objectId && (prop as IColumnSchema).type === 'integer') continue;
                addProps[name] =
                    required.has(name) && name !== objectId
                        ? (prop as TSchema)
                        : Type.Optional(prop as TSchema);
            }

            const getName = `${subject}${objectCapitalized}Get`;
            if (!existing.has(getName)) {
                handlers[getName] = async function (params: Record<string, unknown>) {
                    const {select = '*', ...where} = params;
                    return knex(tableName).where(where).first(select);
                };
                schemas[getName] = Type.Function(
                    [Type.Object({[objectId]: idSchema})],
                    Type.Promise(entitySchema),
                );
            }

            const findName = `${subject}${objectCapitalized}Find`;
            if (!existing.has(findName)) {
                handlers[findName] = async function (params: Record<string, unknown>) {
                    const {select = '*', order, limit, offset, ...where} = params;
                    let query = knex(tableName).where(where);
                    if (order) query = query.orderBy(order as string);
                    if (limit) query = query.limit(limit as number);
                    if (offset) query = query.offset(offset as number);
                    return query.select(select);
                };
                schemas[findName] = Type.Function(
                    [
                        Type.Object({
                            ...allOptionalProps,
                            select: Type.Optional(Type.String()),
                            order: Type.Optional(Type.String()),
                            limit: Type.Optional(Type.Integer()),
                            offset: Type.Optional(Type.Integer()),
                        }),
                    ],
                    Type.Promise(Type.Array(entitySchema)),
                );
            }

            const addName = `${subject}${objectCapitalized}Add`;
            if (!existing.has(addName)) {
                handlers[addName] = async function (params: Record<string, unknown>) {
                    return {
                        [objectId]: (await knex(tableName).insert(params))?.[0],
                    };
                };
                schemas[addName] = Type.Function(
                    [Type.Object(addProps)],
                    Type.Promise(
                        Type.Object({[objectId]: idSchema}),
                    ),
                );
            }

            const editName = `${subject}${objectCapitalized}Edit`;
            if (!existing.has(editName)) {
                handlers[editName] = async function (params: Record<string, unknown>) {
                    const {key: keyName = objectId, ...columns} = params;
                    const {[keyName as string]: key, ...update} = columns;
                    return knex(tableName)
                        .where({[keyName as string]: key})
                        .update(update);
                };
                schemas[editName] = Type.Function(
                    [
                        Type.Object({
                            [objectId]: idSchema,
                            ...allOptionalProps,
                        }),
                    ],
                    Type.Promise(
                        Type.Integer({description: 'Number of affected rows'}),
                    ),
                );
            }

            const removeName = `${subject}${objectCapitalized}Remove`;
            if (!existing.has(removeName)) {
                handlers[removeName] = async function (params: Record<string, unknown>) {
                    return knex(tableName)
                        .where({[objectId]: params[objectId]})
                        .del();
                };
                schemas[removeName] = Type.Function(
                    [Type.Object({[objectId]: idSchema})],
                    Type.Promise(
                        Type.Integer({description: 'Number of affected rows'}),
                    ),
                );
            }

            const mergeName = `${subject}${objectCapitalized}Merge`;
            if (!existing.has(mergeName)) {
                handlers[mergeName] = async function (params: Record<string, unknown>) {
                    return knex(tableName)
                        .insert(params)
                        .onConflict(objectId)
                        .merge();
                };
                schemas[mergeName] = Type.Function(
                    [
                        Type.Object(
                            Object.fromEntries(
                                Object.entries(schema.properties).map(([k, v]) => [
                                    k,
                                    v as TSchema,
                                ]),
                            ),
                        ),
                    ],
                    Type.Promise(Type.Unknown()),
                );
            }

            return {handlers, schemas};
        },
);