diff --git a/lib/DBSchemaBuilder.ts b/lib/DBSchemaBuilder.ts index ed568171..f03cefba 100644 --- a/lib/DBSchemaBuilder.ts +++ b/lib/DBSchemaBuilder.ts @@ -10,11 +10,7 @@ import { } from "prostgles-types"; import prostgles from "."; import { Auth } from "./Auth/AuthTypes"; -import { - DboBuilder, - escapeTSNames, - postgresToTsType, -} from "./DboBuilder/DboBuilder"; +import { DboBuilder, escapeTSNames, postgresToTsType } from "./DboBuilder/DboBuilder"; import { PublishAllOrNothing, PublishParams, @@ -22,28 +18,14 @@ import { PublishViewRule, } from "./PublishParser/PublishParser"; import { getJSONBSchemaTSTypes } from "./JSONBValidation/validation"; -import { - DBHandlerServer, - TableSchemaColumn, - TX, -} from "./DboBuilder/DboBuilderTypes"; +import { DBHandlerServer, TableSchemaColumn, TX } from "./DboBuilder/DboBuilderTypes"; export const getDBSchema = (dboBuilder: DboBuilder): string => { const tables: string[] = []; - const getColTypeForDBSchema = ( - udt_name: TableSchemaColumn["udt_name"], - ): string => { + const getColTypeForDBSchema = (udt_name: TableSchemaColumn["udt_name"]): string => { if (udt_name === "interval") { - const units = [ - "years", - "months", - "days", - "hours", - "minutes", - "seconds", - "milliseconds", - ]; + const units = ["years", "months", "days", "hours", "minutes", "seconds", "milliseconds"]; return `{ ${units.map((u) => `${u}?: number;`).join(" ")} }`; } @@ -56,23 +38,13 @@ export const getDBSchema = (dboBuilder: DboBuilder): string => { ?.slice(0) .sort((a, b) => a.name.localeCompare(b.name)) .forEach((tov) => { - const cols = tov.columns - .slice(0) - .sort((a, b) => a.name.localeCompare(b.name)); + const cols = tov.columns.slice(0).sort((a, b) => a.name.localeCompare(b.name)); const getColType = (c: (typeof cols)[number]) => { let type: string = - (c.is_nullable ? "null | " : "") + - getColTypeForDBSchema(c.udt_name) + - ";"; - const colConf = dboBuilder.prostgles.tableConfigurator?.getColumnConfig( - tov.name, - c.name, - ); + (c.is_nullable ? "null | " : "") + getColTypeForDBSchema(c.udt_name) + ";"; + const colConf = dboBuilder.prostgles.tableConfigurator?.getColumnConfig(tov.name, c.name); if (colConf) { - if ( - isObject(colConf) && - (colConf.jsonbSchema || colConf.jsonbSchemaType) - ) { + if (isObject(colConf) && (colConf.jsonbSchema || colConf.jsonbSchemaType)) { const schema: JSONB.JSONBSchema = colConf.jsonbSchema || { ...colConf, type: colConf.jsonbSchemaType, @@ -82,13 +54,11 @@ export const getDBSchema = (dboBuilder: DboBuilder): string => { schema, { nullable: colConf.nullable }, " ", - dboBuilder.tablesOrViews ?? [], + dboBuilder.tablesOrViews ?? [] ); } else if (isObject(colConf) && "enum" in colConf) { if (!colConf.enum) throw "colConf.enum missing"; - const types = colConf.enum.map((t) => - typeof t === "number" ? t : JSON.stringify(t), - ); + const types = colConf.enum.map((t) => (typeof t === "number" ? t : JSON.stringify(t))); if (colConf.nullable) { types.unshift("null"); } @@ -110,7 +80,7 @@ export const getDBSchema = (dboBuilder: DboBuilder): string => { columns: {${cols .map( (c) => ` - ${getColType(c)}`, + ${getColType(c)}` ) .join("")} }; @@ -132,11 +102,12 @@ type ServerTableHandler< Schema extends DBSchema | void = void, > = TableHandler & { is_view: boolean }; -export type DBTableHandlersFromSchema = Schema extends DBSchema - ? { - [tov_name in keyof Schema]: Schema[tov_name]["is_view"] extends true - ? ServerViewHandler - : ServerTableHandler; +export type DBTableHandlersFromSchema = + Schema extends DBSchema ? + { + [tov_name in keyof Schema]: Schema[tov_name]["is_view"] extends true ? + ServerViewHandler + : ServerTableHandler; } : Record>; @@ -147,29 +118,20 @@ export type DBHandlerServerExtra< sql: SQLHandler; } & Partial & (WithTransactions extends true ? { tx: TX } : Record); -// export type DBOFullyTyped = Schema extends DBSchema? ( -// DBTableHandlersFromSchema & DBHandlerServerExtra> -// ) : -// DBHandlerServer; + export type DBOFullyTyped = DBTableHandlersFromSchema & DBHandlerServerExtra>; -export type PublishFullyTyped = Schema extends DBSchema - ? - | PublishAllOrNothing - | { - [tov_name in keyof Partial]: - | PublishAllOrNothing - | (Schema[tov_name]["is_view"] extends true - ? PublishViewRule - : PublishTableRule); - } - : - | PublishAllOrNothing - | Record< - string, - PublishViewRule | PublishTableRule | PublishAllOrNothing - >; +export type PublishFullyTyped = + Schema extends DBSchema ? + { + [tov_name in keyof Partial]: + | PublishAllOrNothing + | (Schema[tov_name]["is_view"] extends true ? + PublishViewRule + : PublishTableRule); + } + : Record; /** Type checks */ () => { diff --git a/lib/PublishParser/PublishParser.ts b/lib/PublishParser/PublishParser.ts index 8871ebb7..93162053 100644 --- a/lib/PublishParser/PublishParser.ts +++ b/lib/PublishParser/PublishParser.ts @@ -16,9 +16,11 @@ import { RULE_TO_METHODS, TableRule, } from "./publishTypesAndUtils"; +import { ProstglesInitOptions } from "../ProstglesTypes"; +import { PublishFullyTyped } from "../DBSchemaBuilder"; export class PublishParser { - publish: any; + publish: ProstglesInitOptions["publish"]; publishMethods?: PublishMethods | undefined; publishRawSQL?: any; dbo: DBHandlerServer; @@ -86,10 +88,11 @@ export class PublishParser { /** * Parses the first level of publish. (If false then nothing if * then all tables and views) - * @param socket - * @param user */ - async getPublish(localParams: LocalParams, clientInfo?: AuthResult): Promise { + async getPublish( + localParams: LocalParams, + clientInfo?: AuthResult + ): Promise { const publishParams = await this.getPublishParams(localParams, clientInfo); const _publish = await applyParamsIfFunc(this.publish, publishParams); @@ -101,7 +104,7 @@ export class PublishParser { return publish; } - return _publish; + return _publish || undefined; } async getValidatedRequestRuleWusr({ tableName, diff --git a/lib/PublishParser/getSchemaFromPublish.ts b/lib/PublishParser/getSchemaFromPublish.ts index 2ff196e8..aae546c6 100644 --- a/lib/PublishParser/getSchemaFromPublish.ts +++ b/lib/PublishParser/getSchemaFromPublish.ts @@ -49,7 +49,7 @@ export async function getSchemaFromPublish( throw err; } - if (Object.keys(_publish).length) { + if (_publish && Object.keys(_publish).length) { let txKey = "tx"; if (!this.prostgles.opts.transactions) txKey = ""; if (typeof this.prostgles.opts.transactions === "string") diff --git a/lib/PublishParser/getTableRulesWithoutFileTable.ts b/lib/PublishParser/getTableRulesWithoutFileTable.ts index 194421f3..f26549fa 100644 --- a/lib/PublishParser/getTableRulesWithoutFileTable.ts +++ b/lib/PublishParser/getTableRulesWithoutFileTable.ts @@ -22,14 +22,11 @@ export async function getTableRulesWithoutFileTable( ): Promise { // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!localParams || !tableName) - throw { - stack: ["getTableRules()"], - message: "publish OR socket OR dbo OR tableName are missing", - }; + throw new Error("publish OR socket OR dbo OR tableName are missing"); const _publish = overridenPublish ?? (await this.getPublish(localParams, clientInfo)); - const raw_table_rules = _publish[tableName]; + const raw_table_rules = _publish?.[tableName]; if ( !raw_table_rules || (isObject(raw_table_rules) && Object.values(raw_table_rules).every((v) => !v)) diff --git a/lib/PublishParser/publishTypesAndUtils.ts b/lib/PublishParser/publishTypesAndUtils.ts index 7434e597..942833ee 100644 --- a/lib/PublishParser/publishTypesAndUtils.ts +++ b/lib/PublishParser/publishTypesAndUtils.ts @@ -1,10 +1,4 @@ -import { - AnyObject, - DBSchema, - FullFilter, - Method, - RULE_METHODS, -} from "prostgles-types"; +import { AnyObject, DBSchema, FullFilter, Method, RULE_METHODS } from "prostgles-types"; import type { DBOFullyTyped, PublishFullyTyped } from "../DBSchemaBuilder"; import { CommonTableRules, @@ -15,11 +9,8 @@ import { } from "../DboBuilder/DboBuilder"; import { DB, DBHandlerServer } from "../Prostgles"; -export type PublishMethods< - S = void, - SUser extends SessionUser = SessionUser, -> = ( - params: PublishParams, +export type PublishMethods = ( + params: PublishParams ) => { [key: string]: Method } | Promise<{ [key: string]: Method } | null>; export type Awaitable = T | Promise; @@ -171,10 +162,7 @@ export type DeleteRequestData = { filter: object; returning: FieldFilter; }; -export type UpdateRequestDataOne< - R extends AnyObject, - S extends DBSchema | void = void, -> = { +export type UpdateRequestDataOne = { filter: FullFilter; data: Partial; returning: FieldFilter; @@ -195,42 +183,28 @@ export type ValidateRowArgs = { dbx: DBX; localParams: LocalParams; }; -export type ValidateUpdateRowArgs< - U = Partial, - F = Filter, - DBX = DBHandlerServer, -> = { +export type ValidateUpdateRowArgs, F = Filter, DBX = DBHandlerServer> = { update: U; filter: F; dbx: DBX; localParams: LocalParams; }; export type ValidateRow = ( - args: ValidateRowArgs>, + args: ValidateRowArgs> ) => R | Promise; export type PostValidateRow = ( - args: ValidateRowArgs>, -) => void | Promise; -export type PostValidateRowBasic = ( - args: ValidateRowArgs, + args: ValidateRowArgs> ) => void | Promise; -export type ValidateRowBasic = ( - args: ValidateRowArgs, -) => AnyObject | Promise; -export type ValidateUpdateRow< - R extends AnyObject = AnyObject, - S extends DBSchema | void = void, -> = ( - args: ValidateUpdateRowArgs, FullFilter, DBOFullyTyped>, +export type PostValidateRowBasic = (args: ValidateRowArgs) => void | Promise; +export type ValidateRowBasic = (args: ValidateRowArgs) => AnyObject | Promise; +export type ValidateUpdateRow = ( + args: ValidateUpdateRowArgs, FullFilter, DBOFullyTyped> ) => Partial | Promise>; export type ValidateUpdateRowBasic = ( - args: ValidateUpdateRowArgs, + args: ValidateUpdateRowArgs ) => AnyObject | Promise; -export type SelectRule< - Cols extends AnyObject = AnyObject, - S extends DBSchema | void = void, -> = { +export type SelectRule = { /** * Fields allowed to be selected. * Tip: Use false to exclude field @@ -261,9 +235,7 @@ export type SelectRule< /** * Validation logic to check/update data for each request */ - validate?( - args: SelectRequestData, - ): SelectRequestData | Promise; + validate?(args: SelectRequestData): SelectRequestData | Promise; }; export type CommonInsertUpdateRule< @@ -311,9 +283,7 @@ export type InsertRule< * Validation logic to check/update data after the insert. * Happens in the same transaction so upon throwing an error the record will be deleted (not committed) */ - postValidate?: S extends DBSchema - ? PostValidateRow, S> - : PostValidateRowBasic; + postValidate?: S extends DBSchema ? PostValidateRow, S> : PostValidateRowBasic; /** * If defined then only nested inserts from these tables are allowed @@ -365,23 +335,16 @@ export type UpdateRule< /** * Validation logic to check/update data for each request */ - validate?: S extends DBSchema - ? ValidateUpdateRow - : ValidateUpdateRowBasic; + validate?: S extends DBSchema ? ValidateUpdateRow : ValidateUpdateRowBasic; /** * Validation logic to check/update data after the insert. * Happens in the same transaction so upon throwing an error the record will be deleted (not committed) */ - postValidate?: S extends DBSchema - ? PostValidateRow, S> - : PostValidateRowBasic; + postValidate?: S extends DBSchema ? PostValidateRow, S> : PostValidateRowBasic; }; -export type DeleteRule< - Cols extends AnyObject = AnyObject, - S extends DBSchema | void = void, -> = { +export type DeleteRule = { /** * Filter added to every query (e.g. user_id) to restrict access */ @@ -448,10 +411,7 @@ export type TableRule< sync?: SyncRule; subscribe?: SubscribeRule; }; -export type PublishViewRule< - Col extends AnyObject = AnyObject, - S extends DBSchema | void = void, -> = { +export type PublishViewRule = { select?: SelectRule | PublishAllOrNothing; getColumns?: PublishAllOrNothing; getInfo?: PublishAllOrNothing; @@ -495,19 +455,14 @@ export type PublishParams = { export type RequestParams = { dbo?: DBHandlerServer; socket?: any }; export type PublishAllOrNothing = boolean | "*" | null; export type PublishObject = { - [table_name: string]: - | PublishTableRule - | PublishViewRule - | PublishAllOrNothing; + [table_name: string]: PublishTableRule | PublishViewRule | PublishAllOrNothing; }; export type ParsedPublishTables = { [table_name: string]: ParsedPublishTable; }; -export type PublishedResult = - | PublishAllOrNothing - | PublishFullyTyped; + +type PublishAllOrNothingRoot = Exclude; +export type PublishedResult = PublishAllOrNothingRoot | PublishFullyTyped; export type Publish = | PublishedResult - | (( - params: PublishParams, - ) => Awaitable>); + | ((params: PublishParams) => Awaitable>); diff --git a/package-lock.json b/package-lock.json index 35be8ed2..43dcb43d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "prostgles-server", - "version": "4.2.188", + "version": "4.2.189", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "prostgles-server", - "version": "4.2.188", + "version": "4.2.189", "license": "MIT", "dependencies": { "@aws-sdk/client-ses": "^3.699.0", diff --git a/package.json b/package.json index 6b1dd5ee..3463132f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "prostgles-server", - "version": "4.2.188", + "version": "4.2.189", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/tests/server/package-lock.json b/tests/server/package-lock.json index 464decd2..42979bd7 100644 --- a/tests/server/package-lock.json +++ b/tests/server/package-lock.json @@ -21,7 +21,7 @@ }, "../..": { "name": "prostgles-server", - "version": "4.2.188", + "version": "4.2.189", "license": "MIT", "dependencies": { "@aws-sdk/client-ses": "^3.699.0", diff --git a/tests/server/publishTypeCheck.ts b/tests/server/publishTypeCheck.ts index 8875f4e0..16fbcb76 100644 --- a/tests/server/publishTypeCheck.ts +++ b/tests/server/publishTypeCheck.ts @@ -1,3 +1,4 @@ +import { ProstglesInitOptions } from "../../dist/ProstglesTypes"; import { DBGeneratedSchema } from "./DBGeneratedSchema"; import { PublishFullyTyped } from "prostgles-server/dist/DBSchemaBuilder"; @@ -18,7 +19,7 @@ export const testPublishTypes = () => { }, items3: "*", }; - const p2: PublishFullyTyped = "*"; + const p2: ProstglesInitOptions["publish"] = "*"; const p11: PublishFullyTyped = { items: { @@ -39,7 +40,7 @@ export const testPublishTypes = () => { //@ts-ignore const p1234: PublishFullyTyped = p1; - const p12: PublishFullyTyped = "*"; + const p12: ProstglesInitOptions["publish"] = "*"; const res: PublishFullyTyped = { shapes: "*", @@ -63,12 +64,13 @@ export const testPublishTypes = () => { }, items4: { - select: Math.random() - ? "*" - : { + select: + Math.random() ? "*" : ( + { fields: { name: 0 }, forcedFilter: { name: "abc" }, - }, + } + ), insert: "*", update: "*", delete: "*", diff --git a/tsconfig.json b/tsconfig.json index 5a8c5108..ba5f66fa 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -18,6 +18,7 @@ "declaration": true, "skipLibCheck": true, "declarationMap": true, + "noImplicitAny": true }, "exclude": [ "dist"