UNPKG

23.1 kBJavaScriptView Raw
1"use strict";
2var __assign = (this && this.__assign) || function () {
3 __assign = Object.assign || function(t) {
4 for (var s, i = 1, n = arguments.length; i < n; i++) {
5 s = arguments[i];
6 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7 t[p] = s[p];
8 }
9 return t;
10 };
11 return __assign.apply(this, arguments);
12};
13var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15 return new (P || (P = Promise))(function (resolve, reject) {
16 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19 step((generator = generator.apply(thisArg, _arguments || [])).next());
20 });
21};
22var __generator = (this && this.__generator) || function (thisArg, body) {
23 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25 function verb(n) { return function (v) { return step([n, v]); }; }
26 function step(op) {
27 if (f) throw new TypeError("Generator is already executing.");
28 while (_) try {
29 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30 if (y = 0, t) op = [op[0] & 2, t.value];
31 switch (op[0]) {
32 case 0: case 1: t = op; break;
33 case 4: _.label++; return { value: op[1], done: false };
34 case 5: _.label++; y = op[1]; op = [0]; continue;
35 case 7: op = _.ops.pop(); _.trys.pop(); continue;
36 default:
37 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41 if (t[2]) _.ops.pop();
42 _.trys.pop(); continue;
43 }
44 op = body.call(thisArg, _);
45 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47 }
48};
49var __importDefault = (this && this.__importDefault) || function (mod) {
50 return (mod && mod.__esModule) ? mod : { "default": mod };
51};
52Object.defineProperty(exports, "__esModule", { value: true });
53var gridfs_stream_1 = __importDefault(require("gridfs-stream"));
54var http_1 = __importDefault(require("http"));
55var https_1 = __importDefault(require("https"));
56var koa_1 = __importDefault(require("koa"));
57var koa_compress_1 = __importDefault(require("koa-compress"));
58var koa_convert_1 = __importDefault(require("koa-convert"));
59var koa_body_1 = __importDefault(require("koa-body"));
60var koa_json_1 = __importDefault(require("koa-json"));
61var koa_logger_1 = __importDefault(require("koa-logger"));
62var koa_send_1 = __importDefault(require("koa-send"));
63var koa_static_1 = __importDefault(require("koa-static"));
64var koa_static_cache_1 = __importDefault(require("koa-static-cache"));
65var koa_session_1 = __importDefault(require("koa-session"));
66var mongoose_1 = __importDefault(require("mongoose"));
67var path_1 = __importDefault(require("path"));
68var ServerApp = /** @class */ (function () {
69 function ServerApp(config, env) {
70 if (env === void 0) { env = process.env.NODE_ENV || 'development'; }
71 this.config = config;
72 this._app = new koa_1.default();
73 this._servers = [];
74 this.env = env;
75 }
76 Object.defineProperty(ServerApp.prototype, "name", {
77 get: function () {
78 return this.config.name;
79 },
80 enumerable: true,
81 configurable: true
82 });
83 Object.defineProperty(ServerApp.prototype, "dbConn", {
84 get: function () {
85 return this._dbConn;
86 },
87 enumerable: true,
88 configurable: true
89 });
90 Object.defineProperty(ServerApp.prototype, "grid", {
91 get: function () {
92 return this._grid;
93 },
94 enumerable: true,
95 configurable: true
96 });
97 Object.defineProperty(ServerApp.prototype, "app", {
98 get: function () {
99 return this._app;
100 },
101 enumerable: true,
102 configurable: true
103 });
104 Object.defineProperty(ServerApp.prototype, "servers", {
105 get: function () {
106 return this._servers;
107 },
108 enumerable: true,
109 configurable: true
110 });
111 Object.defineProperty(ServerApp.prototype, "env", {
112 get: function () {
113 return this.app.env;
114 },
115 set: function (environment) {
116 this.app.env = environment;
117 },
118 enumerable: true,
119 configurable: true
120 });
121 ServerApp.prototype.start = function () {
122 return __awaiter(this, void 0, void 0, function () {
123 var err_1, err_2, _i, _a, m, _b, _c, r, _loop_1, this_1, _d, _e, dir, _loop_2, this_2, _f, _g, s, _loop_3, this_3, _h, _j, s, _k, _l, socket, _m, _o, server, err_3;
124 var _this = this;
125 return __generator(this, function (_p) {
126 switch (_p.label) {
127 case 0:
128 _p.trys.push([0, 7, , 8]);
129 if (!this.config.mongoUris) return [3 /*break*/, 5];
130 _p.label = 1;
131 case 1:
132 _p.trys.push([1, 3, , 4]);
133 return [4 /*yield*/, mongoose_1.default.connect(this.config.mongoUris, __assign({ useNewUrlParser: true, useUnifiedTopology: true }, this.config.mongooseConnectionOptions))];
134 case 2:
135 _p.sent();
136 this._dbConn = mongoose_1.default.connection;
137 console.log("Database connected to " + this.config.mongoUris + ".");
138 this._grid = gridfs_stream_1.default(this._dbConn.db, mongoose_1.default.mongo);
139 return [3 /*break*/, 4];
140 case 3:
141 err_1 = _p.sent();
142 err_1.message = "Database connection error: " + err_1.message;
143 throw err_1;
144 case 4:
145 if (this.config.models) {
146 // Create collections for models provided in IServerAppConfig ahead-of-time
147 // needed for first-time ACID transactions
148 // (timeout is needs to give mongoose sometime to register all models)
149 setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
150 var _i, _a, model, name, collection;
151 return __generator(this, function (_b) {
152 switch (_b.label) {
153 case 0:
154 if (!this._dbConn)
155 return [2 /*return*/];
156 _i = 0, _a = this.config.models || [];
157 _b.label = 1;
158 case 1:
159 if (!(_i < _a.length)) return [3 /*break*/, 5];
160 model = _a[_i];
161 name = mongoose_1.default.pluralize()(model.modelName);
162 return [4 /*yield*/, this._dbConn.db
163 .listCollections({ name: name })
164 .next()];
165 case 2:
166 collection = _b.sent();
167 if (!!collection) return [3 /*break*/, 4];
168 return [4 /*yield*/, this._dbConn.createCollection(name)];
169 case 3:
170 _b.sent();
171 console.info("Created '" + name + "' collection.");
172 _b.label = 4;
173 case 4:
174 _i++;
175 return [3 /*break*/, 1];
176 case 5: return [2 /*return*/];
177 }
178 });
179 }); }, 5000);
180 }
181 return [3 /*break*/, 6];
182 case 5:
183 if (this.config.models) {
184 // else if there are models but no mongoUris... what are they for?
185 throw new Error('No MongoDB URI to load the provided models on.');
186 }
187 _p.label = 6;
188 case 6: return [3 /*break*/, 8];
189 case 7:
190 err_2 = _p.sent();
191 err_2.message = "Mongoose setup error: " + err_2.message;
192 throw err_2;
193 case 8:
194 _p.trys.push([8, 10, , 11]);
195 // set keys
196 if (this.config.keys)
197 this.app.keys = this.config.keys;
198 // use the essential koa middleware
199 if (this.config.log !== false) {
200 this.app.use(koa_logger_1.default());
201 }
202 if (this.config.session !== false &&
203 Array.isArray(this.app.keys) &&
204 this.app.keys.length) {
205 this.app.use(koa_session_1.default({
206 key: this.config.sessionCookieKey ||
207 this.config.name
208 .trim()
209 .toLowerCase()
210 .replace(/ /g, '_'),
211 httpOnly: this.config.sessionHttpOnly !== false,
212 maxAge: this.config.sessionMaxAge || 86400000,
213 overwrite: this.config.sessionOverwrite !== false,
214 renew: this.config.sessionRenew || false,
215 rolling: this.config.sessionRolling || false,
216 signed: this.config.sessionSigned !== false
217 }, this.app));
218 }
219 if (this.config.compress !== false) {
220 this.app.use(koa_compress_1.default({
221 level: 9,
222 memLevel: 9,
223 threshold: 0
224 }));
225 }
226 if (this.config.bodyParser !== false) {
227 this.app.use(koa_body_1.default({
228 encoding: this.config.bodyParserEncoding || 'utf-8',
229 formLimit: this.config.bodyParserFormLimit || '56kb',
230 json: this.config.bodyParserEnableJson !== false,
231 jsonLimit: this.config.bodyParserJsonLimit || '1mb',
232 multipart: this.config.bodyParserMultipart || false,
233 text: this.config.bodyParserEnableText !== false,
234 textLimit: this.config.bodyParserTextLimit || '1mb',
235 urlencoded: this.config.bodyParserEnableForm !== false
236 }));
237 }
238 if (this.config.json !== false) {
239 this.app.use(koa_json_1.default({
240 pretty: this.config.jsonPretty || this.env === 'development',
241 param: this.config.jsonPrettyParam || undefined,
242 spaces: this.config.jsonSpaces || 2
243 }));
244 }
245 // use provided middleware
246 if (this.config.middleware)
247 for (_i = 0, _a = this.config.middleware; _i < _a.length; _i++) {
248 m = _a[_i];
249 this.app.use(koa_convert_1.default.compose(m));
250 }
251 // use provided routers
252 if (this.config.routers)
253 for (_b = 0, _c = this.config.routers; _b < _c.length; _b++) {
254 r = _c[_b];
255 this.app.use(r.routes()).use(r.allowedMethods());
256 }
257 // use provided public directories (with static cache)
258 if (this.config.publicDirs) {
259 _loop_1 = function (dir) {
260 if (!this_1.config.cacheFiles)
261 this_1.config.cacheFiles = {};
262 var cacheFiles = __assign({}, this_1.config.cacheFiles);
263 for (var pathKey in cacheFiles) {
264 if (!cacheFiles.hasOwnProperty(pathKey))
265 continue;
266 var value = cacheFiles[pathKey];
267 delete cacheFiles[pathKey];
268 // normalize paths
269 cacheFiles[path_1.default.normalize(decodeURIComponent(pathKey))] = value;
270 }
271 var originalCacheFilesFreeze = JSON.stringify(__assign({}, cacheFiles));
272 this_1.app.use(function (ctx, next) { return __awaiter(_this, void 0, void 0, function () {
273 var occ, pathKey, file;
274 return __generator(this, function (_a) {
275 switch (_a.label) {
276 case 0: return [4 /*yield*/, next()];
277 case 1:
278 _a.sent();
279 occ = JSON.parse(originalCacheFilesFreeze);
280 for (pathKey in occ) {
281 if (occ.hasOwnProperty(pathKey) &&
282 path_1.default.normalize(decodeURIComponent(ctx.path)) === pathKey) {
283 file = occ[pathKey];
284 if (!file || (!file.cacheControl && file.maxAge != undefined))
285 break;
286 ctx.set('cache-control', "" + (file.cacheControl ||
287 this.config.cacheControl ||
288 'private') + (file.maxAge != undefined ? ', max-age=' + file.maxAge : ''));
289 break;
290 }
291 }
292 return [2 /*return*/];
293 }
294 });
295 }); });
296 this_1.app.use(koa_static_cache_1.default(dir, __assign({ cacheControl: this_1.config.cacheControl || 'private' }, this_1.config.cacheOptions), cacheFiles));
297 this_1.app.use(koa_static_1.default(dir, {
298 gzip: this_1.config.compress === true || this_1.config.compress === false
299 ? this_1.config.compress
300 : true
301 }));
302 };
303 this_1 = this;
304 for (_d = 0, _e = this.config.publicDirs; _d < _e.length; _d++) {
305 dir = _e[_d];
306 _loop_1(dir);
307 }
308 }
309 // 404 => SPA?
310 if (this.config.spaFileRelativePath) {
311 this.app.use(function (ctx) { return __awaiter(_this, void 0, void 0, function () {
312 return __generator(this, function (_a) {
313 switch (_a.label) {
314 case 0:
315 if (!(ctx.status === 404)) return [3 /*break*/, 2];
316 return [4 /*yield*/, koa_send_1.default(ctx, this.config.spaFileRelativePath).catch(function (err) {
317 return console.error("Error sending the specified SPA file: " + err);
318 })];
319 case 1:
320 _a.sent();
321 _a.label = 2;
322 case 2: return [2 /*return*/];
323 }
324 });
325 }); });
326 }
327 // create and listen on all https servers
328 if (this.config.httpsServers) {
329 _loop_2 = function (s) {
330 var server = https_1.default
331 .createServer(s.opts, this_2.app.callback())
332 .listen(s.port, s.hostname || s.path, function (err) {
333 if (err) {
334 err.message = "HTTPS server creation error: " + err.message;
335 throw err;
336 }
337 var address = server.address();
338 console.log("Listening at " + (!address
339 ? 'unknown address'
340 : typeof address === 'string'
341 ? address
342 : 'https://' + address.address + ':' + address.port + '/') + " in " + _this.app.env + " mode.");
343 });
344 this_2.servers.push(server);
345 };
346 this_2 = this;
347 for (_f = 0, _g = this.config.httpsServers; _f < _g.length; _f++) {
348 s = _g[_f];
349 _loop_2(s);
350 }
351 }
352 // create and listen on all http servers
353 if (this.config.httpServers) {
354 _loop_3 = function (s) {
355 var server = http_1.default
356 .createServer(this_3.app.callback())
357 .listen(s.port, s.hostname || s.path, function (err) {
358 if (err) {
359 err.message = "HTTP server creation error: " + err.message;
360 throw err;
361 }
362 var address = server.address();
363 console.log("Listening at " + (!address
364 ? 'unknown address'
365 : typeof address === 'string'
366 ? address
367 : 'http://' + address.address + ':' + address.port + '/') + " in " + _this.app.env + " mode.");
368 });
369 this_3.servers.push(server);
370 };
371 this_3 = this;
372 for (_h = 0, _j = this.config.httpServers; _h < _j.length; _h++) {
373 s = _j[_h];
374 _loop_3(s);
375 }
376 }
377 // attach sockets to the servers
378 if (this.config.sockets) {
379 for (_k = 0, _l = this.config.sockets; _k < _l.length; _k++) {
380 socket = _l[_k];
381 for (_m = 0, _o = this.servers; _m < _o.length; _m++) {
382 server = _o[_m];
383 socket.attach(server);
384 }
385 }
386 }
387 return [4 /*yield*/, Promise.resolve()];
388 case 9: return [2 /*return*/, _p.sent()];
389 case 10:
390 err_3 = _p.sent();
391 err_3.message = "Koa setup error: " + err_3.message;
392 throw err_3;
393 case 11: return [2 /*return*/];
394 }
395 });
396 });
397 };
398 return ServerApp;
399}());
400exports.ServerApp = ServerApp;
401//# sourceMappingURL=server-app.js.map
\No newline at end of file