Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,29 @@ app.start();
// open http://localhost:8088/test
```

## More Examples

- Validation

> see [validatorjs](https://github.com/mikeerickson/validatorjs) for more rules

```javascript
const { Router } = require("@axiosleo/koapp");

const router = new Router("/test", {
method: "any",
validator: {
query: {
name: "required|string",
},
body: {
age: "required|integer",
}
}
handlers: [],
});
```

## License

This project is open-sourced software licensed under the [MIT](LICENSE).
Expand Down
22 changes: 22 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,28 @@ if (require.main === module) {
handlers: [async () => {
Model.create({}, { param: 'required' });
}]
}), new Router('/validate', {
method: 'any',
validators: {
query: {
rules: {
a: 'required',
b: 'string'
}
},
body: {
rules: {
bodyA: 'required',
bodyB: 'string'
},
messages: {
'required': 'The :attribute field is required......'
}
}
},
handlers: [async (context) => {
success('all params is valid');
}]
})]
});
app.start();
Expand Down
14 changes: 11 additions & 3 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import type KoaStaticServer from 'koa-static-server';
import type Koa from 'koa';
import type { Context, Configuration } from '@axiosleo/cli-tool';
import type { IncomingHttpHeaders } from 'http';

import type { Rules, ErrorMessages, Validator } from 'validatorjs';

type StatusCode = string | '000;Unknown Error' |
Expand Down Expand Up @@ -59,10 +58,19 @@ export declare class Controller implements ControllerInterface {
log(...data: any): void;
}

interface RouterValidator {
rules: Rules,
messages?: ErrorMessages
}

interface RouterInfo {
pathinfo: string;
handlers: ContextHandler[];
validators: {
query: RouterValidator,
body: RouterValidator
};
middlewares: ContextHandler[];
handlers: ContextHandler[];
params: {
[key: string]: string;
};
Expand Down Expand Up @@ -169,4 +177,4 @@ export declare class Model {
count(): number;

validate(rules: Rules, msg?: ErrorMessages): Validator<this>;
}
}
36 changes: 35 additions & 1 deletion src/app.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
'use strict';

const { Configuration, Workflow } = require('@axiosleo/cli-tool');
const { Configuration, Workflow, debug } = require('@axiosleo/cli-tool');
const { _foreach } = require('@axiosleo/cli-tool/src/helper/cmd');
const EventEmitter = require('events');
const { v4, v5, validate } = require('uuid');
const Validator = require('validatorjs');
const { failed } = require('./response');
const is = require('@axiosleo/cli-tool/src/helper/is');

const resolvePathinfo = (pathinfo) => {
let trace = [];
Expand Down Expand Up @@ -124,6 +127,7 @@ const getRouteInfo = (routers, pathinfo, method) => {
const routeInfo = {
pathinfo,
params: {},
validators: route.router.validators ? route.router.validators : {},
handlers: route.router.handlers ? route.router.handlers : [],
middlewares: route.middlewares,
};
Expand Down Expand Up @@ -167,6 +171,7 @@ class Application extends EventEmitter {
constructor(config) {
super();
this.config = new Configuration({
debug: false,
routers: [],
app_id: '',
...config,
Expand All @@ -177,6 +182,32 @@ class Application extends EventEmitter {
begin: async (context) => {
this.trigger('receive', context);
},
validate: async (context) => {
this.trigger('validate', context);
if (context.router && context.router.validators) {
const { query, body } = context.router.validators;
const check = {};
if (query) {
const validation = new Validator(context.params, query.rules, query.messages || null);
validation.check();
if (validation.fails()) {
const errors = validation.errors.all();
check.query = errors;
}
}
if (body) {
const validation = new Validator(context.body, body.rules, body.messages || null);
validation.check();
if (validation.fails()) {
const errors = validation.errors.all();
check.body = errors;
}
}
if (!is.empty(check)) {
failed(check, '400;Bad Request Data');
}
}
},
middleware: async (context) => {
this.trigger('middleware', context);

Expand Down Expand Up @@ -227,6 +258,9 @@ class Application extends EventEmitter {
const router = getRouteInfo(routes, ctx.path, ctx.method);
if (!router) {
this.trigger('notFound', context);
if (this.config.debug) {
debug.log('[RouterNotFound]', ctx.path, ctx.method);
}
await next();
return;
}
Expand Down