import DateTime from "@entity-access/entity-access/dist/types/DateTime.js"; import FetchBuilder from "@web-atoms/fetch-builder"; export type IPrimitive = number | boolean | string | bigint | Date | DateTime | null; export default class QueryBuilder { private methods = []; private start = 0; private size = 20; private trace = void 0; private count = false; private more = void 0; constructor( private fb: FetchBuilder, private name: string, private fx?: string, private args?: IPrimitive[] ) { } public async first() { const { items: [first] = [] } = await this .range(0, 1) .toPage(); return first ?? null; } public save(e: T) { return this.fb .post("/social-mail/api/entity/") .jsonBody(e) .asJson(); } public delete(e: T) { return this.fb .delete("/social-mail/api/entity/") .jsonBody(e) .asJson(); } public toPage () { const { start, size, methods, trace, more = true, fx, args } = this; return this.fb.get(`/social-mail/api/entity/query/${this.name}`) .queries({ start, size, trace, more, count: false, function: fx, args: args?.length ? JSON.stringify(args) : void 0, methods: JSON.stringify(methods) }) .asJson<{ items: (T & { $type: string })[], more: boolean }>(); } public toPagedList () { const { start, size, methods, trace, count, fx, args } = this; return this.fb.get(`/social-mail/api/entity/query/${this.name}`) .queries({ start, size, trace, count, function: fx, args: args?.length ? JSON.stringify(args) : void 0, methods: JSON.stringify(methods) }) .asJson<{ items: (T & { $type: string })[], total: number }>(); } public range( start = 0, size = 100) { const c = this.clone(); c.start = start; c.size = size; return c; } public offset(start) { const c = this.clone(); c.start = start; return c; } public limit(size) { const c = this.clone(); c.size = size; return c; } public traceQuery(trace) { const c = this.clone(); c.trace = trace; return c; } where

(pm: P, fx: (p: P) => (x: T) => boolean) { return this.append("where", pm, fx); } orderBy

(pm: P, fx: (p: P) => (x: T) => any) { return this.append("orderBy", pm, fx); } orderByDescending

(pm: P, fx: (p: P) => (x: T) => boolean) { return this.append("orderByDescending", pm, fx); } thenBy

(pm: P, fx: (p: P) => (x: T) => boolean) { return this.append("thenBy", pm, fx); } thenByDescending

(pm: P, fx: (p: P) => (x: T) => boolean) { return this.append("thenByDescending", pm, fx); } private append(name: string, pm, fx) { const c = this.clone(); let q = fx(null).toString(); const values = []; const [_, pName] = /\(?([a-z\$\_][a-z0-9\$\_]{0,20})\)?/gm.exec(fx.toString().trim()) ?? []; for (const key in pm) { if (Object.hasOwn(pm, key)) { const element = pm[key]; const index = values.length; values.push(element); q = q.replaceAll(`${pName}.${key}`,`@${index}`); } } c.methods.push([name, q, ... values]); return c; } private clone() { const c = { ... this, methods: [ ... this.methods ] }; Object.setPrototypeOf(c, QueryBuilder.prototype); return c as QueryBuilder; } }