UNPKG

2.65 kBtext/coffeescriptView Raw
1'use strict'
2
3MemoryResource = require './memory-resource'
4
5###*
6
7@class MasterDataResource
8@implements ResourceClientInterface
9###
10class MasterDataResource
11
12 ###*
13 load master JSON file if exists
14
15 @constructor
16 ###
17 constructor: (@facade) ->
18
19 { dirname } = @facade
20
21 @masterDirPath = @constructor.getDirPath(dirname)
22 @masterJSONPath = @constructor.getJSONPath(dirname)
23 @memories = {}
24
25
26 ###*
27 Get master data dir
28
29 @method getDirPath
30 @public
31 @static
32 @return {String}
33 ###
34 @getDirPath: (dirname) -> dirname + '/master-data'
35
36 ###*
37 Get master JSON path
38
39 @method getJSONPath
40 @public
41 @static
42 @return {String}
43 ###
44 @getJSONPath: (dirname) -> @getDirPath(dirname) + '/all.json'
45
46
47 ###*
48 load data from directory(Node.js) or JSON (other environments)
49
50 @method init
51 @public
52 @chainable
53 ###
54 init: ->
55
56 if not Ti? and not window?
57 @build()
58
59 else
60 plainMemories = @loadFromJSON()
61
62 for modelName, plainMemory of plainMemories
63 @memories[modelName] = MemoryResource.restore(plainMemory)
64
65 @
66
67
68 initWithData: (data) ->
69 for modelName, plainMemory of data
70 @memories[modelName] = MemoryResource.restore(plainMemory)
71
72 @
73
74
75 ###*
76 load data from JSON file
77
78 @method loadFromJSON
79 @private
80 ###
81 loadFromJSON: ->
82
83 { requireJSON } = @facade.constructor # only defined in Node.js
84
85 try
86 return requireJSON @masterJSONPath
87
88 catch e
89 console.error("""
90 base-domain: [warning] MasterDataResource could not load from path '#{@masterJSONPath}'
91 """)
92
93
94 ###*
95 Get memory resource of the given modelName
96 @method getMemoryResource
97 @return {MemoryResource}
98 ###
99 getMemoryResource: (modelName) ->
100 @memories[modelName] ?= new MemoryResource
101
102
103 ###*
104 Create JSON file from tsv files (**only called by Node.js**)
105
106 @method build
107 ###
108 build: ->
109
110 FixtureLoader = require './fixture-loader'
111
112 new FixtureLoader(@facade, @masterDirPath).load()
113 { fs } = @facade.constructor # only defined in Node.js
114 fs.writeFileSync @masterJSONPath, JSON.stringify @toPlainObject(), null, 1
115
116
117 ###*
118 Create plain object
119
120 @method toPlainObject
121 @return {Object} plainObject
122 ###
123 toPlainObject: ->
124
125 plainObj = {}
126
127 for modelName, memory of @memories
128
129 plainObj[modelName] = memory.toPlainObject()
130
131 return plainObj
132
133
134module.exports = MasterDataResource