-
Notifications
You must be signed in to change notification settings - Fork 153
/
rest-hapi.js
293 lines (239 loc) Β· 6.91 KB
/
rest-hapi.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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
'use strict'
const extend = require('extend')
const _ = require('lodash')
const path = require('path')
const Inert = require('@hapi/inert')
const Vision = require('@hapi/vision')
const Joi = require('joi')
const HapiSwagger = require('hapi-swagger')
const Mrhorse = require('mrhorse')
const logging = require('loggin')
const logUtil = require('./utilities/log-util')
const chalk = require('chalk')
const restHelperFactory = require('./utilities/rest-helper-factory')
const handlerHelper = require('./utilities/handler-helper')
const joiHelper = require('./utilities/joi-mongoose-helper')
const testHelper = require('./utilities/test-helper')
const modelGenerator = require('./utilities/model-generator')
const apiGenerator = require('./utilities/api-generator')
const defaultConfig = require('./config')
const globals = require('./globals')
const internals = {
modelsGenerated: false,
globalModels: {}
}
module.exports = {
plugin: {
name: 'rest-hapi',
version: '1.0.0',
register
},
config: defaultConfig,
generateModels: generateModels,
list: handlerHelper.list,
find: handlerHelper.find,
create: handlerHelper.create,
update: handlerHelper.update,
deleteOne: handlerHelper.deleteOne,
deleteMany: handlerHelper.deleteMany,
addOne: handlerHelper.addOne,
removeOne: handlerHelper.removeOne,
addMany: handlerHelper.addMany,
removeMany: handlerHelper.removeMany,
getAll: handlerHelper.getAll,
logger: {},
getLogger: getLogger,
logUtil: logUtil,
joi: {},
joiHelper: joiHelper,
testHelper: testHelper,
server: {},
models: {}
}
async function register(server, options) {
module.exports.server = server
// Register Joi as the default validator if one is not already registered.
if (!server.realm.validator) {
server.validator(Joi)
module.exports.joi = Joi
} else {
module.exports.joi = server.realm.validator
}
const config = defaultConfig
// Overwrite the default config with config set by the user
extend(true, config, options.config)
module.exports.config = config
const Log = getLogger('api')
module.exports.logger = Log
// Add the logger object to the request object for access later
server.ext('onRequest', (request, h) => {
request.logger = Log
return h.continue
})
const mongoose = mongooseInit(options.mongoose, Log, config)
logUtil.logActionStart(Log, 'Initializing Server')
let models
if (internals.modelsGenerated) {
// Models generated previously
models = internals.globalModels
} else {
try {
models = await modelGenerator(mongoose, Log, config)
} catch (err) {
if (err.message.includes('no such file')) {
Log.error(
'The policies directory provided does not exist. ' +
"Try setting the 'policyPath' property of the config file."
)
} else {
throw err
}
}
}
module.exports.models = models
if (!config.disableSwagger) {
await registerHapiSwagger(server, Log, config)
}
await registerMrHorse(server, Log, config)
await generateRoutes(server, mongoose, models, Log, config)
}
/**
* Allows the user to pre-generate the models before the routes in case the models are needed
* in other plugins (ex: auth plugin might require user model)
* @param mongoose
* @returns {*}
*/
function generateModels(mongoose) {
internals.modelsGenerated = true
const config = defaultConfig
extend(true, config, module.exports.config)
const Log = getLogger('models')
module.exports.logger = Log
return modelGenerator(mongoose, Log, config).then(function(models) {
internals.globalModels = models
module.exports.models = models
return models
})
}
/**
* Get a new Log object with a root label.
* @param label: The root label for the Log.
* @returns {*}
*/
function getLogger(label) {
const config = defaultConfig
extend(true, config, module.exports.config)
const rootLogger = logging.getLogger(chalk.gray(label))
rootLogger.logLevel = config.loglevel
return rootLogger
}
/**
* Connect mongoose and add to globals.
* @param mongoose
* @param logger
* @param config
* @returns {*}
*/
function mongooseInit(mongoose, logger, config) {
const Log = logger.bind('mongoose-init')
mongoose.Promise = Promise
logUtil.logActionStart(
Log,
'Connecting to Database',
_.omit(config.mongo, ['pass'])
)
const options = Object.assign(
{
useNewUrlParser: true,
useUnifiedTopology: true
},
config.mongo.options
)
mongoose.connect(config.mongo.URI, options)
globals.mongoose = mongoose
Log.log('mongoose connected')
return mongoose
}
/**
* Register and configure the mrhorse plugin.
* @param server
* @param logger
* @param config
* @returns {Promise<void>}
*/
async function registerMrHorse(server, logger, config) {
const Log = logger.bind('register-MrHorse')
let policyPath = ''
if (config.enablePolicies) {
if (config.absolutePolicyPath === true) {
policyPath = config.policyPath
} else {
policyPath = __dirname.replace(
path.join('node_modules', 'rest-hapi'),
config.policyPath
)
}
} else {
policyPath = path.join(__dirname, '/policies')
}
await server.register([
{
plugin: Mrhorse,
options: {
policyDirectory: policyPath
}
}
])
if (config.enablePolicies) {
await server.plugins.mrhorse.loadPolicies(server, {
policyDirectory: path.join(__dirname, '/policies')
})
}
Log.info('MrHorse plugin registered')
}
/**
* Register and configure the hapi-swagger plugin.
* @param server
* @param logger
* @param config
* @returns {Promise<void>}
*/
async function registerHapiSwagger(server, logger, config) {
const Log = logger.bind('register-hapi-swagger')
let swaggerOptions = {
documentationPath: '/',
host: config.swaggerHost,
expanded: config.docExpansion,
swaggerUI: config.enableSwaggerUI,
documentationPage: config.enableSwaggerUI,
schemes: config.enableSwaggerHttps ? ['https'] : ['http']
}
// if swagger config is defined, use that
if (config.swaggerOptions) {
swaggerOptions = { ...swaggerOptions, ...config.swaggerOptions }
}
// override some options for safety
if (!swaggerOptions.info) {
swaggerOptions.info = {}
}
swaggerOptions.info.title = config.appTitle
swaggerOptions.info.version = config.version
swaggerOptions.reuseDefinitions = false
await server.register([
Inert,
Vision,
{ plugin: HapiSwagger, options: swaggerOptions }
])
Log.info('hapi-swagger plugin registered')
}
function generateRoutes(server, mongoose, models, logger, config) {
const Log = logger.bind()
const restHelper = restHelperFactory(logger, mongoose, server)
for (const modelKey in models) {
// Generate endpoints for all of the models
const model = models[modelKey]
restHelper.generateRoutes(server, model, { models: models })
}
// Generate custom endpoints
return apiGenerator(server, mongoose, Log, config)
}