forked from jackiealex/nobone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnobone.coffee
131 lines (113 loc) · 2.51 KB
/
nobone.coffee
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
###*
* NoBone has several modules and a helper lib.
* **All the modules are optional**.
* Only the `kit` lib is loaded by default and is not optional.
*
* Most of the async functions are implemented with [Promise][Promise].
* [Promise]: https://github.com/petkaantonov/bluebird
###
Overview = 'nobone'
_ = require 'lodash'
kit = require './kit'
{ Promise } = kit
###*
* Main constructor.
* @param {Object} modules By default, it only load two modules,
* `service` and `renderer`:
* ```coffeescript
* {
* service: {}
* renderer: {}
* db: null
* proxy: null
*
* lang_dir: null # language set directory
* }
* ```
* @param {Object} opts Other options.
* @return {Object} A nobone instance.
###
nobone = (modules, opts = {}) ->
modules ?= {
db: null
proxy: null
service: {}
renderer: {}
}
_.defaults opts, {
lang_dir: null
}
nb = {
kit
}
for k, v of modules
if modules[k]
nb[k] = require('./modules/' + k)(v)
if nb.service and nb.service.sse and nb.renderer
nb.renderer.on 'file_modified', (path, ext_bin, req_path) ->
nb.service.sse.emit(
'file_modified'
{ path, ext_bin, req_path }
'/auto_reload'
)
# Load language.
kit.lang_load opts.lang_dir
###*
* Release the resources.
* @return {Promise}
###
close = ->
Promise.all _.map(modules, (v, k) ->
mod = nb[k]
if v and mod.close
if mod.close.length > 0
Promise.promisify(mod.close, mod)()
else
Promise.resolve mod.close()
)
nb.close = close
nb
_.extend nobone, {
kit
###*
* The NoBone client helper.
* @static
* @param {Object} opts The options of the client, defaults:
* ```coffeescript
* {
* auto_reload: kit.is_development()
* lang_current: kit.lang_current
* lang_data: kit.lang_data
* host: '' # The host of the event source.
* }
* ```
* @param {Boolean} use_js By default use html. Default is false.
* @return {String} The code of client helper.
###
client: (opts = {}, use_js = false) ->
if nobone.client_js_cache
js = nobone.client_js_cache
else
js = kit.fs.readFileSync(__dirname + '/../dist/nobone_client.js')
nobone.client_js_cache = js
opts_str = JSON.stringify _.defaults(opts, {
auto_reload: kit.is_development()
lang_current: kit.lang_current
lang_data: kit.lang_data
host: ''
})
js = """
\n#{js}
window.nb = new Nobone(#{opts_str});\n
"""
if use_js
js
else
"""
\n\n<!-- Nobone Client Helper -->
<script type="text/javascript">
#{js}
</script>\n\n
"""
}
module.exports = nobone