1 | Container = require './container'
|
2 |
|
3 | isRelative = (path) -> path.indexOf('.') == 0
|
4 |
|
5 | getFullPath = (path, basePath) ->
|
6 | if window?
|
7 | return path
|
8 | else if isRelative path
|
9 | return [ basePath, path ].join '/'
|
10 | else
|
11 | return [ basePath, 'node_modules', path ].join '/'
|
12 |
|
13 | evaluateType = (moduleConfig, module) ->
|
14 | return moduleConfig.type if moduleConfig.type?
|
15 | path = moduleConfig.require || moduleConfig
|
16 | if typeof module == 'function' && isRelative path
|
17 | return 'factory'
|
18 | else
|
19 | return 'value'
|
20 |
|
21 | getPath = (moduleConfig) ->
|
22 | if typeof moduleConfig == 'string'
|
23 | return moduleConfig
|
24 | else
|
25 | return moduleConfig.require
|
26 |
|
27 | clearCache = (modules, basePath) ->
|
28 | Object.keys(modules).forEach (key) ->
|
29 | moduleConfig = modules[key]
|
30 | path = getPath moduleConfig
|
31 | fullPath = getFullPath path, basePath
|
32 | delete require.cache[require.resolve(fullPath)]
|
33 |
|
34 | populateContainer = (di, modules, basePath) ->
|
35 | clearCache(modules, basePath) if options?.clearCache == true
|
36 |
|
37 | Object.keys(modules).forEach (key) ->
|
38 | moduleConfig = modules[key]
|
39 | path = getPath moduleConfig
|
40 | fullPath = getFullPath path, basePath
|
41 | try
|
42 | module = require fullPath
|
43 | catch e
|
44 | module = require path
|
45 | type = evaluateType moduleConfig, module
|
46 | if type == 'factory'
|
47 | di.factory key, module
|
48 | else
|
49 | di.value key, module
|
50 |
|
51 | module.exports = (options) ->
|
52 | { config, basePath, opts, parents } = options
|
53 | throw new TypeError('No configuration was provided for loadConfig') unless config?
|
54 | di = new Container opts, parents
|
55 | modules = config.modules || {}
|
56 | configParents = config.parents || []
|
57 | configParents.forEach (p) ->
|
58 | parentModules = require [ p.nodeModule, p.configFile ].join '/'
|
59 | populateContainer(di, parentModules.modules, p.nodeModule)
|
60 | populateContainer(di, modules, basePath)
|
61 |
|
62 | return di
|