1 | 'use strict'
|
2 |
|
3 | const { $useMiddleware } = require('../symbols')
|
4 |
|
5 | module.exports = {
|
6 | schema: {
|
7 | use: ['string', 'function'],
|
8 | options: {
|
9 | type: 'object',
|
10 | defaultValue: {}
|
11 | }
|
12 | },
|
13 | validate: async mapping => {
|
14 | let factory
|
15 | if (typeof mapping.use === 'function') {
|
16 | factory = mapping.use
|
17 | } else {
|
18 | factory = require(mapping.use)
|
19 | }
|
20 | const middleware = factory(mapping.options)
|
21 | if (middleware.length !== 3) {
|
22 | throw new Error('Unexpected middleware signature')
|
23 | }
|
24 | mapping[$useMiddleware] = middleware
|
25 | },
|
26 | redirect: ({ mapping, request, response }) => new Promise((resolve, reject) => {
|
27 | const next = err => {
|
28 | if (err) {
|
29 | reject(err)
|
30 | } else {
|
31 | resolve()
|
32 | }
|
33 | }
|
34 | try {
|
35 | mapping[$useMiddleware](request, response, next)
|
36 | } catch (err) {
|
37 | reject(err)
|
38 | }
|
39 | })
|
40 | }
|