2020-04-22 22:11:19 +02:00
|
|
|
import { Request, Response } from 'express';
|
2020-04-23 18:58:06 +02:00
|
|
|
import { KnexCrudOptions, Authorization } from './DatabaseCrudOptions';
|
2020-04-22 22:11:19 +02:00
|
|
|
|
|
|
|
type AuthRunner = {
|
|
|
|
(req: Request, res: Response): Promise<boolean>;
|
|
|
|
}
|
|
|
|
|
|
|
|
export class KnexCrudOptionsReader {
|
|
|
|
private options: KnexCrudOptions;
|
|
|
|
|
|
|
|
public constructor (options: KnexCrudOptions) {
|
|
|
|
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) => {
|
|
|
|
const result = auth (req, res, resolve);
|
|
|
|
if (typeof result !== 'undefined')
|
|
|
|
resolve (result as boolean);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
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;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|