Compare commits

..

No commits in common. "1541018701090ce97f37ef0f67e6a0b2b92560a5" and "fccd69db74f0b3c27e4d9a826b31f24907fbb5bf" have entirely different histories.

9 changed files with 4177 additions and 4078 deletions

View File

@ -1,8 +1,8 @@
import { Request, Response } from 'express'; import { Request, Response } from 'express';
export interface CrudHandler { export interface CrudHandler {
create(req: Request, res: Response): Promise<void>; public create(req: Request, res: Response): Promise<void>;
read(req: Request, res: Response): Promise<void>; public read(req: Request, res: Response): Promise<void>;
update(req: Request, res: Response): Promise<void>; public update(req: Request, res: Response): Promise<void>;
delete(req: Request, res: Response): Promise<void>; public delete(req: Request, res: Response): Promise<void>;
} }

View File

@ -1,33 +1,35 @@
import { Request, Response, Router } from 'express'; import { Request, Response, Router } from 'express';
import { http } from '@scode/consts'; import { http } from '@scode/consts';
import { ControlModel, DatabaseModel } from '@scode/modelling'; import { DatabaseCrudOptions } from './DatabaseCrudOptions';
import { CrudHandler } from './CrudHandler'; import { CrudHandler } from './CrudHandler';
import { HttpHandler } from './HttpHandler'; import { HttpHandler } from './HttpHandler';
import { DatabaseCrudOptionsReader } from './DatabaseCrudOptionsReader'; import { DatabaseCrudOptionsReader } from './DatabaseCrudOptionsReader';
import { DatabaseCrudOptions } from './DatabaseCrudOptions';
export class DatabaseCrudHandler extends HttpHandler implements CrudHandler { export class DatabaseCrudHandler extends HttpHandler implements CrudHandler {
protected cm: protected table: string;
new (object: Record<string, string|number|boolean>) => ControlModel; protected columns: Array<string>;
protected dm: new (id?: number) => DatabaseModel;
protected options: DatabaseCrudOptionsReader; protected options: DatabaseCrudOptionsReader;
public constructor ( public constructor (
cm: new (object: Record<string, string|number|boolean>) => ControlModel, table: string,
dm: new (id?: number) => DatabaseModel, columns: Array<string>,
options: DatabaseCrudOptions = {} options: DatabaseCrudOptions = {}
) { ) {
super (); super ();
this.cm = cm; this.table = table;
this.dm = dm; this.columns = columns;
this.options = new DatabaseCrudOptionsReader (options); this.options = new DatabaseCrudOptionsReader (options);
if (this.columns.filter ((val) => val.toLowerCase () === 'id').length > 0) {
throw new Error (
'the column id cannot be made available to modification'
);
}
} }
protected validate_body ( protected validate_body (
req: Request, req: Request,
res: Response res: Response
): Promise<Record<string, unknown> | null> | Record<string, unknown> | null { ): Promise<Record<string, unknown>> | Record<string, unknown> {
if (typeof req.body === 'undefined') { if (typeof req.body === 'undefined') {
res.status (http.status_bad_request); res.status (http.status_bad_request);
res.end ('body was undefined'); res.end ('body was undefined');
@ -43,6 +45,29 @@ export class DatabaseCrudHandler extends HttpHandler implements CrudHandler {
return null; return null;
} }
protected ensure_data (
data: Record<string, unknown>,
res: Response,
fail_on_undef = true
): Promise<Record<string, unknown>> | Record<string, unknown> {
const obj = {};
const keys = Object.keys (data);
for (const col of this.columns) {
if (!keys.includes (col) && fail_on_undef) {
res.status (http.status_bad_request)
.end (`missing field: ${col}`);
return null;
}
obj[col] = data[col];
}
if (typeof this.options.optional_columns !== 'undefined') {
for (const col of this.options.optional_columns)
obj[col] = data[col];
}
return obj;
}
public async create (req: Request, res: Response): Promise<void> { public async create (req: Request, res: Response): Promise<void> {
if (!await this.options.create_authorization (req, res)) if (!await this.options.create_authorization (req, res))
return; return;
@ -51,16 +76,16 @@ export class DatabaseCrudHandler extends HttpHandler implements CrudHandler {
if (body_data === null) if (body_data === null)
return; return;
const cm = new this.cm (body_data as Record<string|string, number|boolean>); const db_data = await this.ensure_data (body_data, res);
cm.update (); if (db_data === null)
return;
const dm = new this.dm; const inserted = await this.knex (this.table)
for (const key of Object.keys (body_data)) .returning ('id')
dm.set (key, cm.get (key)); .insert (db_data);
await dm.write ();
res.status (http.status_created) res.status (http.status_created)
.end (dm.id); .end (inserted[0]);
} }
public async read (req: Request, res: Response): Promise<void> { public async read (req: Request, res: Response): Promise<void> {
@ -73,14 +98,14 @@ export class DatabaseCrudHandler extends HttpHandler implements CrudHandler {
return; return;
} }
const dm = new this.dm (parseInt (req.headers.id as string)); const json = await this.knex (this.table)
const found = await dm.read (); .where ({ id: req.headers.id })
.select (
const cm = new this.cm (dm.object); 'id',
cm.update (); ...this.columns
);
res.status (found ? http.status_ok : http.status_not_found) res.status (json.length > 0 ? http.status_ok : http.status_not_found)
.json (cm.object); .json (json[0]);
} }
public async update (req: Request, res: Response): Promise<void> { public async update (req: Request, res: Response): Promise<void> {
@ -91,33 +116,21 @@ export class DatabaseCrudHandler extends HttpHandler implements CrudHandler {
if (body_data === null) if (body_data === null)
return; return;
const db_data = await this.ensure_data (body_data, res, false);
if (db_data === null)
return;
if (typeof req.headers.id === 'undefined') { if (typeof req.headers.id === 'undefined') {
res.status (http.status_bad_request) res.status (http.status_bad_request)
.end ('id undefined'); .end ('id undefined');
return; return;
} }
const dm = new this.dm (parseInt (req.headers.id as string)); await this.knex (this.table)
const found = await dm.read (); .where ({ id: req.headers.id })
if (!found) { .update (db_data);
res.status (http.status_not_found)
.end ();
return;
}
const cm = new this.cm (dm.object); res.status (http.status_ok)
cm.update ();
for (const key of Object.keys (body_data))
cm.set (key, body_data[key] as string|number|boolean);
cm.update ();
for (const key of Object.keys (cm.object))
dm.set (key, cm.get (key));
const written = await dm.write ();
res.status (written ? http.status_ok : http.status_internal_server_error)
.end (); .end ();
} }
@ -131,17 +144,11 @@ export class DatabaseCrudHandler extends HttpHandler implements CrudHandler {
return; return;
} }
const dm = new this.dm (parseInt (req.headers.id as string)); await this.knex (this.table)
const found = await dm.read (); .where ({ id: req.headers.id })
if (!found) { .delete ();
res.status (http.status_not_found)
.end ();
return;
}
const deleted = await dm.delete (); res.status (http.status_ok)
res.status (deleted ? http.status_ok : http.status_internal_server_error)
.end (); .end ();
} }

View File

@ -1,4 +1,5 @@
import { Request, Response } from 'express'; import { Request, Response } from 'express';
import ControlModel from '@scode/modelling';
type Authorization = { type Authorization = {
(req: Request, res: Response): Promise<boolean>; (req: Request, res: Response): Promise<boolean>;
@ -12,6 +13,7 @@ interface DatabaseCrudOptions {
update_authorization?: Authorization; update_authorization?: Authorization;
delete_authorization?: Authorization; delete_authorization?: Authorization;
optional_columns?: Array<string>; optional_columns?: Array<string>;
control_model?: Type<ControlModel>;
} }
export { Authorization, DatabaseCrudOptions }; export { Authorization, DatabaseCrudOptions };

View File

@ -1,15 +1,15 @@
import { Request, Response } from 'express'; import { Request, Response } from 'express';
import { DatabaseCrudOptions, Authorization } from './DatabaseCrudOptions'; import { KnexCrudOptions, Authorization } from './DatabaseCrudOptions';
type AuthRunner = { type AuthRunner = {
(req: Request, res: Response): Promise<boolean>; (req: Request, res: Response): Promise<boolean>;
} }
export class DatabaseCrudOptionsReader { export class KnexCrudOptionsReader {
private _options: DatabaseCrudOptions; private options: KnexCrudOptions;
public constructor (options: DatabaseCrudOptions) { public constructor (options: KnexCrudOptions) {
this._options = options; this.options = options;
} }
private get_auth_runner ( private get_auth_runner (
@ -17,28 +17,20 @@ export class DatabaseCrudOptionsReader {
): AuthRunner { ): AuthRunner {
if (typeof auth === 'undefined') if (typeof auth === 'undefined')
return (): Promise<boolean> => new Promise ((r) => r (true)); return (): Promise<boolean> => new Promise ((r) => r (true));
return (req, res): Promise<boolean> => new Promise ( return (req, res): Promise<boolean> => new Promise ((resolve) => {
(resolve: (value: boolean) => void) => { const result = auth (req, res, resolve);
(async (): Promise<void> => { if (typeof result !== 'undefined')
let resolved = false; resolve (result as boolean);
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 { public get optional_columns (): Array<string> | undefined {
return this._options.optional_columns; return this.options.optional_columns;
} }
public get create_authorization (): Authorization { public get create_authorization (): Authorization {
const general = this.get_auth_runner (this._options.general_authorization); const general = this.get_auth_runner (this.options.general_authorization);
const specific = this.get_auth_runner (this._options.create_authorization); const specific = this.get_auth_runner (this.options.create_authorization);
return async (req: Request, res: Response): Promise<boolean> => { return async (req: Request, res: Response): Promise<boolean> => {
const result = (await general (req, res)) && (await specific (req, res)); const result = (await general (req, res)) && (await specific (req, res));
return result; return result;
@ -46,8 +38,8 @@ export class DatabaseCrudOptionsReader {
} }
public get read_authorization (): Authorization { public get read_authorization (): Authorization {
const general = this.get_auth_runner (this._options.general_authorization); const general = this.get_auth_runner (this.options.general_authorization);
const specific = this.get_auth_runner (this._options.read_authorization); const specific = this.get_auth_runner (this.options.read_authorization);
return async (req: Request, res: Response): Promise<boolean> => { return async (req: Request, res: Response): Promise<boolean> => {
const result = (await general (req, res)) && (await specific (req, res)); const result = (await general (req, res)) && (await specific (req, res));
return result; return result;
@ -55,8 +47,8 @@ export class DatabaseCrudOptionsReader {
} }
public get update_authorization (): Authorization { public get update_authorization (): Authorization {
const general = this.get_auth_runner (this._options.general_authorization); const general = this.get_auth_runner (this.options.general_authorization);
const specific = this.get_auth_runner (this._options.update_authorization); const specific = this.get_auth_runner (this.options.update_authorization);
return async (req: Request, res: Response): Promise<boolean> => { return async (req: Request, res: Response): Promise<boolean> => {
const result = (await general (req, res)) && (await specific (req, res)); const result = (await general (req, res)) && (await specific (req, res));
return result; return result;
@ -64,8 +56,8 @@ export class DatabaseCrudOptionsReader {
} }
public get delete_authorization (): Authorization { public get delete_authorization (): Authorization {
const general = this.get_auth_runner (this._options.general_authorization); const general = this.get_auth_runner (this.options.general_authorization);
const specific = this.get_auth_runner (this._options.delete_authorization); const specific = this.get_auth_runner (this.options.delete_authorization);
return async (req: Request, res: Response): Promise<boolean> => { return async (req: Request, res: Response): Promise<boolean> => {
const result = (await general (req, res)) && (await specific (req, res)); const result = (await general (req, res)) && (await specific (req, res));
return result; return result;

View File

@ -1,6 +1,6 @@
import { Router } from 'express'; import { Router } from 'express';
export abstract class HttpHandler { export class HttpHandler {
public abstract register_handlers(router: Router): void; public abstract register_handlers(router: Router): void;
public get_router (): Router { public get_router (): Router {

View File

@ -4,7 +4,7 @@
"description": "Express handler templates", "description": "Express handler templates",
"main": "dist/index.js", "main": "dist/index.js",
"scripts": { "scripts": {
"test": "echo \"no test\"", "test": "nyc ava",
"compile": "tsc", "compile": "tsc",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx,.vue,.mjs", "lint": "eslint . --ext .js,.jsx,.ts,.tsx,.vue,.mjs",
"ci": "yarn --frozen-lockfile && node jenkins.js" "ci": "yarn --frozen-lockfile && node jenkins.js"
@ -23,17 +23,17 @@
}, },
"devDependencies": { "devDependencies": {
"@ava/typescript": "^1.1.1", "@ava/typescript": "^1.1.1",
"@scode/eslint-config-ts": "^1.0.27", "@scode/eslint-config-ts": "^1.0.22",
"@stryker-mutator/core": "^3.1.0", "@stryker-mutator/core": "^3.1.0",
"@stryker-mutator/javascript-mutator": "^3.1.0", "@stryker-mutator/javascript-mutator": "^3.1.0",
"ava": "^3.8.1", "ava": "^3.7.1",
"eslint": "^6.8.0", "eslint": "^6.8.0",
"nyc": "^15.0.1", "nyc": "^15.0.1",
"typescript": "^3.8.3" "typescript": "^3.8.3"
}, },
"dependencies": { "dependencies": {
"@scode/consts": "^1.1.7", "@scode/consts": "^1.1.5",
"@scode/modelling": "^1.0.16", "@scode/modelling": "^1.0.3",
"@types/express": "^4.17.6", "@types/express": "^4.17.6",
"express": "^4.17.1" "express": "^4.17.1"
} }

20
test/.eslintrc.js Normal file
View File

@ -0,0 +1,20 @@
/*
* Copyright (C) Sapphirecode - All Rights Reserved
* This file is part of Requestor which is released under BSD-3-Clause.
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, March 2020
*/
module.exports = {
env: {
commonjs: true,
es6: true,
node: true
},
extends: [
'@scode/eslint-config-ts'
],
rules: {
'node/no-unpublished-import': 'off'
}
}

88
test/KnexCrudHandler.ts Normal file
View File

@ -0,0 +1,88 @@
import knex from 'knex';
import test from 'ava';
import express, { Request, Response } from 'express';
import { http } from '@scode/consts';
import { KnexCrudHandler } from '../lib/DatabaseCrudHandler';
const db = knex ({
client: 'sqlite',
connection: { filename: './db.sqlite' }
});
/**
* general auth
*
* @param {any} req request
* @param {any} res response
* @returns {Promise<boolean>} successful response
*/
function general_auth (req: Request, res: Response): Promise<boolean> {
return new Promise ((resolve) => {
if (req.headers.auth === 'on') {
resolve (true);
}
else {
res.status (http.status_forbidden);
res.end ('auth failed');
resolve (false);
}
});
}
/**
* read auth
*
* @param {any} req request
* @param {any} res response
* @returns {Promise<boolean>} successful response
*/
function read_auth (req: Request, res: Response): Promise<boolean> {
return new Promise ((resolve) => {
if (req.headers.readauth === 'on') {
resolve (true);
}
else {
res.status (http.status_forbidden);
res.end ('readauth failed');
resolve (false);
}
});
}
test.before (async () => {
await db.schema.dropTableIfExists ('test');
await db.schema.createTable ('test', (t) => {
t.increments ('id');
t.string ('name');
t.integer ('number');
});
const no_auth = new KnexCrudHandler (db, 'test', [
'name',
'number'
], {});
const auth = new KnexCrudHandler (db, 'test', [ 'name' ], {
optional_columns: [ 'number' ],
general_authorization: general_auth,
read_authorization: read_auth
});
const app = express ();
app.use ('/test', no_auth.get_router ());
app.use ('/auth', auth.get_router ());
// eslint-disable-next-line no-magic-numbers
app.listen (3000);
});
test ('insert data', (t) => {});
test ('read data', (t) => {});
test ('update data', (t) => {});
test ('read updated data', (t) => {});
test ('[a] insert data', (t) => {});
test ('[a] insert data without auth', (t) => {});
test ('[a] insert data without optional column', (t) => {});
test ('[a] read data', (t) => {});
test ('[a] read data without auth', (t) => {});
test ('[a] read data without readauth', (t) => {});

7960
yarn.lock

File diff suppressed because it is too large Load Diff