forked from ForestAdmin/forest-express
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
272 lines (240 loc) · 9.34 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
'use strict';
var P = require('bluebird');
var _ = require('lodash');
var express = require('express');
var path = require('path');
var fs = P.promisifyAll(require('fs'));
var cors = require('express-cors');
var bodyParser = require('body-parser');
var jwt = require('express-jwt');
var ResourcesRoutes = require('./routes/resources');
var AssociationsRoutes = require('./routes/associations');
var StatRoutes = require('./routes/stats');
var SessionRoute = require('./routes/sessions');
var ForestRoutes = require('./routes/forest');
var Schemas = require('./generators/schemas');
var JSONAPISerializer = require('jsonapi-serializer').Serializer;
var request = require('superagent');
var logger = require('./services/logger');
var Integrator = require('./integrations');
var errorHandler = require('./services/error-handler');
function requireAllModels(Implementation, modelsDir) {
if (modelsDir) {
return fs.readdirAsync(modelsDir)
.each(function (file) {
try {
require(path.join(modelsDir, file));
} catch (e) { }
})
.then(function () {
return _.values(Implementation.getModels());
})
.catch(function (error) {
if (error.code === 'ENOENT') {
logger.error('Your Forest modelsDir option you configured does not ' +
'seem to be an existing directory.');
} else {
logger.error('Cannot read your models for the following reason: ' +
error);
}
return P.resolve([]);
});
} else {
// NOTICE: User didn't provide a modelsDir but may already have required
// them manually so they might be available.
return P.resolve(_.values(Implementation.getModels()));
}
}
exports.Schemas = Schemas;
exports.logger = logger;
exports.init = function (Implementation) {
var opts = Implementation.opts;
var app = express();
var integrator = new Integrator(opts);
if (opts.secretKey) {
logger.warn('DEPRECATION WARNING: The use of secretKey and authKey options ' +
'is deprecated. Please use envSecret and authSecret instead.');
opts.envSecret = opts.secretKey;
opts.authSecret = opts.authKey;
}
// CORS
app.use(cors({
allowedOrigins: ['localhost:4200', '*.forestadmin.com'],
headers: ['Authorization', 'X-Requested-With', 'Content-Type']
}));
// Mime type
app.use(bodyParser.json());
var jwtAuthenticator;
// Authentication
if (opts.authSecret) {
jwtAuthenticator = jwt({
secret: opts.authSecret,
credentialsRequired: false
});
} else {
logger.error('Your Forest authSecret seems to be missing. Can you check ' +
'that you properly set a Forest authSecret in the Forest initializer?');
}
if (jwtAuthenticator) {
if (opts.expressParentApp) {
// NOTICE: Forest is a sub-app of the client application; so all routes are
// protected with JWT.
app.use(jwtAuthenticator);
} else {
// NOTICE: Forest routes are part of the client app; only Forest routes
// are protected with JWT.
app.use(jwtAuthenticator.unless({ path: /^((?!.*\/forest\/).)*$/ }));
}
}
new SessionRoute(app, opts).perform();
// Init
var absModelDirs = opts.modelsDir ? path.resolve('.', opts.modelsDir) : undefined;
requireAllModels(Implementation, absModelDirs)
.then(function (models) {
return Schemas.perform(Implementation, integrator, models, opts)
.then(function () {
var directorySmartImplementation;
if (opts.configDir) {
directorySmartImplementation = path.resolve('.', opts.configDir);
} else {
directorySmartImplementation = path.resolve('.') + '/forest';
}
return requireAllModels(Implementation, directorySmartImplementation)
.catch(function () {
// The forest/ directory does not exist. It's not a problem.
});
})
.thenReturn(models);
})
.each(function (model) {
integrator.defineRoutes(app, model, Implementation);
new ResourcesRoutes(app, model, Implementation, integrator, opts)
.perform();
new AssociationsRoutes(app, model, Implementation, integrator, opts)
.perform();
new StatRoutes(app, model, Implementation, opts).perform();
})
.then(function () {
new ForestRoutes(app, opts).perform();
})
.then(function () {
app.use(errorHandler.catchIfAny);
})
.then(function () {
if (opts.envSecret && opts.envSecret.length !== 64) {
logger.error('Your envSecret does not seem to be correct. Can you ' +
'check on Forest that you copied it properly in the Forest ' +
'initialization?');
} else {
if (opts.envSecret) {
var collections = _.values(Schemas.schemas);
integrator.defineCollections(Implementation, collections);
// NOTICE: Check each Smart Action declaration to detect configuration
// errors.
_.each(collections, function (collection) {
if (collection.actions) {
_.each(collection.actions, function (action) {
if (action.fields && !_.isArray(action.fields)) {
logger.error('Cannot find the fields you defined for the ' +
'Smart action "' + action.name + '" of your "' +
collection.name + '" collection. The fields option must ' +
'be an array.');
}
});
}
});
var apimap = new JSONAPISerializer('collections', collections, {
id: 'name',
attributes: ['name', 'displayName', 'paginationType', 'icon',
'fields', 'actions', 'segments', 'onlyForRelationships',
'isVirtual', 'isReadOnly'],
fields: {
attributes: ['field', 'displayName', 'type', 'enums',
'collection_name', 'reference', 'column', 'isSearchable',
'widget', 'integration', 'isReadOnly', 'isVirtual']
},
actions: {
ref: 'id',
attributes: ['name', 'endpoint', 'redirect', 'download',
'httpMethod', 'fields']
},
segments: {
ref: 'id',
attributes: ['name']
},
meta: {
'liana': Implementation.getLianaName(),
'liana_version': Implementation.getLianaVersion()
}
});
var forestUrl = process.env.FOREST_URL ||
'https://forestadmin-server.herokuapp.com';
request
.post(forestUrl + '/forest/apimaps')
.send(apimap)
.set('forest-secret-key', opts.envSecret)
.end(function(error, result) {
if (result && result.status !== 204) {
if (result.status === 0) {
logger.warn('Cannot send the apimap to Forest. Are you ' +
'online?');
} else if (result.status === 404) {
logger.error('Cannot find the project related to the ' +
'envSecret you configured. Can you check on Forest ' +
'that you copied it properly in the Forest initialization?');
} else {
logger.error('An error occured with the apimap sent to ' +
'Forest. Please contact [email protected] for ' +
'further investigations.');
}
}
});
}
}
});
if (opts.expressParentApp) {
opts.expressParentApp.use('/forest', app);
}
return app;
};
exports.collection = function (name, opts) {
if (_.isEmpty(Schemas.schemas) && opts.modelsDir) {
logger.error('Cannot customize your collection named "' + name +
'" properly. Did you call the "collection" method in the /forest ' +
'directory?');
return;
}
var collection = _.find(Schemas.schemas, { name: name });
// NOTICE: Action ids are defined concatenating the collection name and the
// action name to prevent action id conflicts between collections.
_.each(opts.actions, function (action) {
action.id = name + '.' + action.name;
});
_.each(opts.segments, function (segment) {
segment.id = name + '.' + segment.name;
});
if (collection) {
if (!Schemas.schemas[name].actions) { Schemas.schemas[name].actions = []; }
if (!Schemas.schemas[name].segments) { Schemas.schemas[name].segments = []; }
Schemas.schemas[name].actions = _.union(opts.actions, Schemas.schemas[name].actions);
Schemas.schemas[name].segments = _.union(opts.segments, Schemas.schemas[name].segments);
opts.fields = _.map(opts.fields, function (field) {
// Smart field
field.isVirtual = true;
field.isSearchable = false;
field.isReadOnly = true;
return field;
});
Schemas.schemas[name].fields = _.concat(opts.fields,
Schemas.schemas[name].fields);
} else {
// NOTICE: Custom collection definition case
opts.name = name;
Schemas.schemas[name] = opts;
}
};
exports.logger = require('./services/logger');
exports.ensureAuthenticated = require('./services/auth').ensureAuthenticated;
exports.StatSerializer = require('./serializers/stat');
exports.ResourceSerializer = require('./serializers/resource');
exports.ResourceDeserializer = require('./deserializers/resource');