import { Request, Response } from 'express'; import { DatabaseCrudOptions, Authorization } from './DatabaseCrudOptions'; type AuthRunner = { (req: Request, res: Response): Promise; } export class DatabaseCrudOptionsReader { private _options: DatabaseCrudOptions; public constructor (options: DatabaseCrudOptions) { this._options = options; } private get_auth_runner ( auth?: Authorization ): AuthRunner { if (typeof auth === 'undefined') return (): Promise => new Promise ((r) => r (true)); return (req, res): Promise => new Promise ( (resolve: (value: boolean) => void) => { (async (): Promise => { let resolved = false; const result = await auth (req, res, (cb: unknown) => { resolved = true; resolve (typeof cb === 'undefined' || cb === true); }); if (!resolved) resolve (result === true); }) (); } ); } public get optional_columns (): Array | undefined { return this._options.optional_columns; } public get create_authorization (): Authorization { const general = this.get_auth_runner (this._options.general_authorization); const specific = this.get_auth_runner (this._options.create_authorization); return async (req: Request, res: Response): Promise => { const result = (await general (req, res)) && (await specific (req, res)); return result; }; } public get read_authorization (): Authorization { const general = this.get_auth_runner (this._options.general_authorization); const specific = this.get_auth_runner (this._options.read_authorization); return async (req: Request, res: Response): Promise => { const result = (await general (req, res)) && (await specific (req, res)); return result; }; } public get update_authorization (): Authorization { const general = this.get_auth_runner (this._options.general_authorization); const specific = this.get_auth_runner (this._options.update_authorization); return async (req: Request, res: Response): Promise => { const result = (await general (req, res)) && (await specific (req, res)); return result; }; } public get delete_authorization (): Authorization { const general = this.get_auth_runner (this._options.general_authorization); const specific = this.get_auth_runner (this._options.delete_authorization); return async (req: Request, res: Response): Promise => { const result = (await general (req, res)) && (await specific (req, res)); return result; }; } }