forked from fullcube/loopback-component-model-extender
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
73 lines (61 loc) · 2.13 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
/* eslint global-require: 0 */
'use strict'
const kebabCase = require('lodash.kebabcase')
const path = require('path')
const debug = require('debug')('loopback:component:model-extender')
const appRoot = require('app-root-path')
const requireAll = require('require-all')
module.exports = (app, options) => {
options = options || {}
debug('applying model customisations. options: %o', options)
function loadComponents(Model) {
debug('configuring model: %s', Model.modelName)
// Sanity checks.
if (Model._componentsLoaded && !options.force) {
debug('cowardly refusing to reload model components')
return
}
Model._componentsLoaded = true
// Set up logging class.
let log = options.log || console
if (typeof log === 'string') {
log = require(log)
}
// Apply models customisations.
function customizeModel(dirname) {
requireAll({
dirname,
recursive: false,
filter: /^([^\.].*)\.(js|ts|json)?$/,
resolve: code => {
debug('Loading customization script %s', code)
if (typeof code === 'function') {
debug('Customizing model %s', Model.modelName)
return code(Model)
}
debug('Skipping model file %s - `module.exports` is not a function', code)
return code
},
})
}
// Determine the path to look for model a customisation file.
const basePath = path.join(appRoot.toString(), (options.basePath || '.'))
const componentsPath = Model.settings.components || `common/models/${kebabCase(Model.modelName)}`
const requirePath = path.join(basePath, componentsPath)
try {
debug(`Searching for model customisation file at ${requirePath}`)
customizeModel(requirePath)
}
catch (err) {
// anything other than 'file not found' should be a hard fail.
if (err.code !== 'ENOENT') {
log.error(`Failure loading component path: ${requirePath}`, err.stack)
throw err
}
}
}
// Loop over each model and apply any found model customisations.
Object.keys(app.models).forEach(key => {
loadComponents(app.models[key])
})
}