1 | "use strict";
|
2 |
|
3 | var path = require('path'),
|
4 | bodyParser = require('body-parser'),
|
5 | fileUpload = require('express-fileupload'),
|
6 | evh = require('express-vhost'),
|
7 | express = require('express'),
|
8 | exists = require('fs-exists-sync'),
|
9 | events = require('./events/index.js'),
|
10 | middleware = require('./middleware/index.js'),
|
11 | server = express(),
|
12 | paths = require('./configs/paths'),
|
13 | config = require('./configs/config');
|
14 |
|
15 |
|
16 | module.exports = () => {
|
17 |
|
18 | this.get = () => {
|
19 | return {
|
20 | model: require('./models'),
|
21 | logger: require('./logs'),
|
22 | view: require('./views'),
|
23 | controller: require('./controllers')
|
24 | }
|
25 | }
|
26 |
|
27 | this.root = config('root') || path.resolve('.');
|
28 |
|
29 | this.paths = paths;
|
30 |
|
31 | this.config = config;
|
32 |
|
33 | this.init = () => {
|
34 | this.env = config('env') || 'development'
|
35 | this.events = new events()
|
36 | this.middleware = new middleware()
|
37 |
|
38 | return true;
|
39 | }
|
40 |
|
41 | this.app = () => {
|
42 | if (this.init()) {
|
43 | var Routes = module.exports.routes = new(require('./routes'))();
|
44 | } else {
|
45 | return false;
|
46 | }
|
47 |
|
48 | if (this.events.exists('createApp')) {
|
49 | return this.exists.emit('createApp', {
|
50 | routes: Routes,
|
51 | controller: Routes.controller,
|
52 | model: Routes.model,
|
53 | view: Routes.view,
|
54 | logger: Routes.logger
|
55 | })
|
56 | } else {
|
57 | var app = express()
|
58 |
|
59 | app.use(bodyParser.urlencoded({
|
60 | extended: false
|
61 | }));
|
62 | app.use(bodyParser.json());
|
63 | app.use(fileUpload());
|
64 |
|
65 | if (this.middleware.exists('express')) {
|
66 | app.use(this.middleware.emit('express', {
|
67 | routes: Routes,
|
68 | controller: Routes.controller,
|
69 | model: Routes.model,
|
70 | view: Routes.view,
|
71 | logger: Routes.logger
|
72 | }))
|
73 | }
|
74 |
|
75 | var publicPath = config('public') || paths.public.public;
|
76 |
|
77 | if (exists(publicPath)) {
|
78 | app.use(express.static(publicPath));
|
79 | }
|
80 |
|
81 | app.use(Routes.auto());
|
82 |
|
83 | return app
|
84 | }
|
85 | }
|
86 |
|
87 | this.cli = (callback) => {
|
88 | var cli = require('./cli')()
|
89 | return callback(cli);
|
90 | return false;
|
91 | }
|
92 |
|
93 | this.start = () => {
|
94 | if (!this.init()) {
|
95 | return false;
|
96 | }
|
97 |
|
98 | var port = config('port'),
|
99 | hostname = config('host') || config('hostname') || config('ip') || false,
|
100 | events = this.events
|
101 |
|
102 |
|
103 | this.app().listen(port, hostname, function() {
|
104 | events.emit('startServer', {
|
105 | port,
|
106 | hostname
|
107 | })
|
108 | if (!hostname) {
|
109 | console.log(`Server running at port ${port}`);
|
110 | } else {
|
111 | console.log(`Server running at http://${hostname}:${port}/`);
|
112 | }
|
113 | });
|
114 | };
|
115 |
|
116 | return this;
|
117 | }
|