UNPKG

2.02 kBJavaScriptView Raw
1'use strict';
2
3var fs = require('fs');
4var serve = require('koa-static');
5var cors = require('koa-cors');
6var jade = require('koa-jade');
7var errorHandlerMiddleware = require('./middlewares/error-handler');
8var methodOverride = require('koa-methodoverride');
9var HookMiddlewareFactory = require('./middlewares/hook');
10var bodyparser = require('koa-bodyparser');
11var requestId = require('koa-request-id');
12
13
14var App = function(koaApp) {
15 this.koaApp = koaApp;
16};
17
18App.prototype = {
19
20 addCorsSupportMiddleware: function() {
21 this.addMiddleware(cors({
22 origin: '*'
23 }));
24 },
25
26
27 loadControllers: function(path) {
28 fs.readdirSync(path).forEach(function (file) {
29 var filePath = path + '/' + file + '/index.js';
30 if (!fs.existsSync(filePath)) return;
31 require(filePath)(this.koaApp);
32 }.bind(this));
33 },
34
35
36 loadModels: function(path) {
37 fs.readdirSync(path).forEach(function (file) {
38 if (/(.*)\.(js$)/.test(file) && !/(.*)\.(spec.js$)/.test(file)) {
39 require(path + '/' + file);
40 }
41 }.bind(this));
42 },
43
44
45 addMiddleware: function(middleware) {
46 this.koaApp.use(middleware);
47 },
48
49
50 addStaticContentMiddleware: function(path) {
51 this.addMiddleware(serve(path));
52 },
53
54
55 addDynamicViewMiddleware: function(root, cache) {
56 this.addMiddleware(jade.middleware({
57 viewPath: root,
58 noCache: !cache
59 }));
60 },
61
62
63 addHookMiddleware: function() {
64 this.addMiddleware(HookMiddlewareFactory.getMiddleware());
65 },
66
67
68 addMethodOverrideMiddleware: function(fieldName) {
69 this.addMiddleware(methodOverride(fieldName));
70 },
71
72
73 addErrorHandlerMiddleware: function() {
74 this.addMiddleware(errorHandlerMiddleware);
75 },
76
77
78 addBodyParseMiddleware: function() {
79 this.addMiddleware(bodyparser());
80 },
81
82
83 addRequestIdmiddleware: function() {
84 this.addMiddleware(requestId());
85 },
86
87
88 listen: function(port, env) {
89 this.koaApp.listen(port);
90 console.log('Application started:', { port: port, env: env });
91 }
92
93};
94
95module.exports = App;