-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.js
47 lines (35 loc) · 1.05 KB
/
example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'use strict';
const bodyParser = require('koa-body');
const fieldValidator = require('./lib');
const koa = require('koa');
const app = koa();
// Middleware depends on koa-body
app.use(bodyParser());
// Use the middleware
app.use(fieldValidator());
// Middleware for handling thrown errors.
app.use(function *(next) {
try {
yield next;
} catch (error) {
const status = error.status || 500;
const message = error.message || 'Internal server error.';
const body = { status: status, message: message };
if (error.fields) {
body.fields = error.fields;
}
this.status = status;
this.body = body;
this.app.emit('error', error, this);
}
});
// General middleware
app.use(function *() {
// Perform validation on the required username field
this.validate('username').isRequired();
// Assert that this.fieldErrors does not exist, throwing 400 if it does
this.assert(!this.fieldErrors, 400, { fields: this.fieldErrors });
// If the assertion was true, we hav no errors
this.body = 'No errors!';
});
app.listen(3000);