1 | /*
|
2 |
|
3 | ----------------------------------------------------------------------------
|
4 | | qewd: Quick and Easy Web Development |
|
5 | | |
|
6 | | Copyright (c) 2017 M/Gateway Developments Ltd, |
|
7 | | Reigate, Surrey UK. |
|
8 | | All rights reserved. |
|
9 | | |
|
10 | | http://www.mgateway.com |
|
11 | | Email: rtweed@mgateway.com |
|
12 | | |
|
13 | | |
|
14 | | Licensed under the Apache License, Version 2.0 (the "License"); |
|
15 | | you may not use this file except in compliance with the License. |
|
16 | | You may obtain a copy of the License at |
|
17 | | |
|
18 | | http://www.apache.org/licenses/LICENSE-2.0 |
|
19 | | |
|
20 | | Unless required by applicable law or agreed to in writing, software |
|
21 | | distributed under the License is distributed on an "AS IS" BASIS, |
|
22 | | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
23 | | See the License for the specific language governing permissions and |
|
24 | | limitations under the License. |
|
25 | ----------------------------------------------------------------------------
|
26 |
|
27 | 5 September 2017
|
28 |
|
29 | Thanks to Ward DeBacker for modifications, in particular
|
30 | for the beforeRouter and afterRouter logic
|
31 |
|
32 | */
|
33 |
|
34 |
|
35 | var koa = require('koa');
|
36 | var app = new koa();
|
37 | var Router = require('koa-better-router');
|
38 | var koaRouter = Router().loadMethods();
|
39 | var koaServe = require('koa-static');
|
40 | var koaBodyParser = require('koa-bodyparser');
|
41 |
|
42 | var bodyParser;
|
43 | var qx;
|
44 | var q;
|
45 |
|
46 | function qxHandleMessage(ctx) {
|
47 | //console.log('!!!! params = ' + JSON.stringify(ctx.params));
|
48 | ctx.state.params = ctx.params;
|
49 | return new Promise((resolve) => {
|
50 | qx.handleMessage(ctx, resolve);
|
51 | })
|
52 | }
|
53 |
|
54 | async function responseTime (ctx, next) {
|
55 | //console.log('in responseTime');
|
56 | const started = Date.now();
|
57 | await next();
|
58 | // once all middleware below completes, this continues
|
59 | const elapsed = (Date.now() - started) + 'ms';
|
60 | ctx.set('X-ResponseTime', elapsed);
|
61 |
|
62 | // if cors is set
|
63 | if (qx.cors) {
|
64 | ctx.set('Access-Control-Allow-Credentials', 'true');
|
65 | ctx.set('Access-Control-Allow-Headers', 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization');
|
66 | ctx.set('Access-Control-Allow-Methods', 'GET, PUT, DELETE, POST, OPTIONS');
|
67 | ctx.set('Access-Control-Allow-Origin', '*');
|
68 | }
|
69 | }
|
70 |
|
71 | function configure(config, routes, qOper8, qExt) {
|
72 | qx = qExt;
|
73 | q = qOper8;
|
74 |
|
75 | // if user instantiates his/her own bodyParser module, use it
|
76 | // Note: user must then also define the app.use express middleware to use it
|
77 |
|
78 | if (config.bodyParser) {
|
79 | bodyParser = config.bodyParser;
|
80 | }
|
81 | else {
|
82 | bodyParser = koaBodyParser;
|
83 | app.use(bodyParser());
|
84 | // note: config.webServer will be 'koa'
|
85 | }
|
86 |
|
87 | // if user defines addMiddleware method, give them complete control!
|
88 |
|
89 | if (config.addMiddleware) config.addMiddleware(bodyParser, app, q, qx, config);
|
90 |
|
91 | app.use(responseTime);
|
92 | app.use(koaServe(config.webServerRootPath));
|
93 |
|
94 | koaRouter.addRoute('GET /ajax/*', async (ctx, next) => {
|
95 | await qxHandleMessage(ctx);
|
96 | await next();
|
97 | });
|
98 | koaRouter.addRoute('POST /ajax/*', async (ctx, next) => {
|
99 | await qxHandleMessage(ctx);
|
100 | await next();
|
101 | });
|
102 |
|
103 | if (config.cors) qx.cors = true;
|
104 |
|
105 | if (routes) {
|
106 | routes.forEach(function(route) {
|
107 | //console.log('** route = ' + JSON.stringify(route));
|
108 | var path = route.path;
|
109 | // create (variable) arguments array to pass to app.use()
|
110 | var args = [];
|
111 |
|
112 | // add array with custom middleware to add before qx.router is called (if present)
|
113 |
|
114 | if (route.beforeRouter && Array.isArray(route.beforeRouter)) args = args.concat(route.beforeRouter);
|
115 |
|
116 | var handler = async (ctx, next) => {
|
117 | //console.log('$$$ params = ' + JSON.stringify(ctx.params));
|
118 | await qxHandleMessage(ctx);
|
119 | await next();
|
120 | };
|
121 |
|
122 | if (route.afterRouter) {
|
123 | handler = async (ctx, next) => {
|
124 | //console.log('$$$ params = ' + JSON.stringify(ctx.params));
|
125 | ctx.state.nextCallback = true;
|
126 | //console.log('$$$ state = ' + JSON.stringify(ctx.state));
|
127 | await qxHandleMessage(ctx);
|
128 | await next();
|
129 | };
|
130 | }
|
131 | args = args.concat([
|
132 | handler
|
133 | ]);
|
134 |
|
135 | // add array with custom middleware to add after qx.router is called (if present)
|
136 |
|
137 | if (route.afterRouter && Array.isArray(route.afterRouter)) args = args.concat(route.afterRouter);
|
138 |
|
139 | // define the Express route by calling app.use()
|
140 |
|
141 | //console.log('add Koa route for path ' + path, args);
|
142 |
|
143 | var match;
|
144 |
|
145 | match = 'GET ' + path + '/:type';
|
146 | koaRouter.addRoute(match, args);
|
147 |
|
148 | match = 'GET ' + path + '/:type/*';
|
149 | koaRouter.addRoute(match, args);
|
150 |
|
151 | match = 'POST ' + path + '/:type/*';
|
152 | koaRouter.addRoute(match, args);
|
153 |
|
154 | match = 'POST ' + path + '/:type';
|
155 | koaRouter.addRoute(match, args);
|
156 |
|
157 | match = 'DELETE ' + path + '/:type/*';
|
158 | koaRouter.addRoute(match, args);
|
159 |
|
160 | match = 'PUT ' + path + '/:type';
|
161 | koaRouter.addRoute(match, args);
|
162 |
|
163 | match = 'PUT ' + path + '/:type/*';
|
164 | koaRouter.addRoute(match, args);
|
165 |
|
166 | match = 'PATCH ' + path + '/:type';
|
167 | koaRouter.addRoute(match, args);
|
168 |
|
169 | match = 'PATCH ' + path + '/:type/*';
|
170 | koaRouter.addRoute(match, args);
|
171 | });
|
172 | }
|
173 |
|
174 | app.use(koaRouter.middleware());
|
175 |
|
176 | // **** if (userIntercept) app.use(demo);
|
177 |
|
178 | // End of middleware chain - display the body
|
179 | app.use(ctx => {
|
180 | //console.log('display!');
|
181 |
|
182 | // only set body if there is a responseObj in ctx.state
|
183 | // (to avoid overwriting error statuses from middleware)
|
184 |
|
185 | !ctx.state.nextCallback && ctx.state.responseObj && (ctx.body = ctx.state.responseObj);
|
186 | });
|
187 | return app;
|
188 | }
|
189 |
|
190 | module.exports = configure
|