This repository has been archived on 2020-08-13. You can view files and clone it, but cannot push or open issues or pull requests.
requestor/lib/DatabaseCrudOptionsReader.ts
2020-05-02 21:48:22 +02:00

75 lines
2.6 KiB
TypeScript

import { Request, Response } from 'express';
import { DatabaseCrudOptions, Authorization } from './DatabaseCrudOptions';
type AuthRunner = {
(req: Request, res: Response): Promise<boolean>;
}
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<boolean> => new Promise ((r) => r (true));
return (req, res): Promise<boolean> => new Promise (
(resolve: (value: boolean) => void) => {
(async (): Promise<void> => {
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<string> | 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<boolean> => {
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<boolean> => {
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<boolean> => {
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<boolean> => {
const result = (await general (req, res)) && (await specific (req, res));
return result;
};
}
}