UNPKG

1.91 kBJavaScriptView Raw
1/* @flow */
2'use strict'
3
4/* ::
5import type {
6 Handler,
7 BmRequest,
8 RouteConfiguration
9} from '../types.js'
10*/
11
12const uniloc = require('uniloc')
13
14const BmResponse = require('../lib/bm-response.js')
15
16function 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 // If a result has been returned:
25 // try and set status code or
26 // try and set payload
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
38function getHandler (
39 module /* : string */,
40 method /* : string */
41) /* : Promise<Handler | void> */ {
42 try {
43 // $FlowIssue in this case, we explicitly `require()` dynamically
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
54function 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
74module.exports = {
75 findRouteConfig,
76 executeHandler,
77 getHandler
78}