1 |
|
2 | 'use strict'
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | const uniloc = require('uniloc')
|
13 |
|
14 | const BmResponse = require('../lib/bm-response.js')
|
15 |
|
16 | function executeHandler (
|
17 | handler /* : Handler */,
|
18 | request /* : BmRequest */
|
19 | ) /* : Promise<BmResponse> */ {
|
20 | const response = new BmResponse()
|
21 | return Promise.resolve()
|
22 | .then(() => handler(request, response))
|
23 | .then((result) => {
|
24 |
|
25 |
|
26 |
|
27 | if (result && result !== response) {
|
28 | if (Number.isFinite(result)) {
|
29 | response.setStatusCode(result)
|
30 | } else {
|
31 | response.setPayload(result)
|
32 | }
|
33 | }
|
34 | return response
|
35 | })
|
36 | }
|
37 |
|
38 | function getHandler (
|
39 | module /* : string */,
|
40 | method /* : string */
|
41 | ) /* : Promise<Handler | void> */ {
|
42 | try {
|
43 |
|
44 | let handler = require(module)
|
45 | if (handler && method && typeof handler[method] === 'function') {
|
46 | handler = handler[method]
|
47 | }
|
48 | return Promise.resolve(handler)
|
49 | } catch (err) {
|
50 | return Promise.reject(err)
|
51 | }
|
52 | }
|
53 |
|
54 | function findRouteConfig (
|
55 | route /* : string */,
|
56 | routeConfigs /* : RouteConfiguration[] */
|
57 | ) /* : RouteConfiguration */ {
|
58 | const unilocRoutes = routeConfigs.reduce((memo, r) => {
|
59 | memo[r.route] = `GET ${r.route.replace(/{/g, ':').replace(/}/g, '')}`
|
60 | return memo
|
61 | }, {})
|
62 | const unilocRouter = uniloc(unilocRoutes)
|
63 | const unilocRoute = unilocRouter.lookup(route, 'GET')
|
64 |
|
65 | const routeConfig = routeConfigs.find((routeConfig) => routeConfig.route === unilocRoute.name)
|
66 | if (!routeConfig) {
|
67 | throw new Error(`Route has not been implemented: ${route}`)
|
68 | }
|
69 |
|
70 | routeConfig.params = unilocRoute.options
|
71 | return routeConfig
|
72 | }
|
73 |
|
74 | module.exports = {
|
75 | findRouteConfig,
|
76 | executeHandler,
|
77 | getHandler
|
78 | }
|