1 | 'use strict'
|
2 |
|
3 | MemoryResource = require './memory-resource'
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | class MasterDataResource
|
11 |
|
12 | |
13 |
|
14 |
|
15 |
|
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 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 | @getDirPath: (dirname) -> dirname + '/master-data'
|
35 |
|
36 | |
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 | @getJSONPath: (dirname) -> @getDirPath(dirname) + '/all.json'
|
45 |
|
46 |
|
47 | |
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
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 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 | loadFromJSON: ->
|
82 |
|
83 | { requireJSON } = @facade.constructor
|
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 |
|
96 |
|
97 |
|
98 |
|
99 | getMemoryResource: (modelName) ->
|
100 | @memories[modelName] ?= new MemoryResource
|
101 |
|
102 |
|
103 | |
104 |
|
105 |
|
106 |
|
107 |
|
108 | build: ->
|
109 |
|
110 | FixtureLoader = require './fixture-loader'
|
111 |
|
112 | new FixtureLoader(@facade, @masterDirPath).load()
|
113 | { fs } = @facade.constructor
|
114 | fs.writeFileSync @masterJSONPath, JSON.stringify @toPlainObject(), null, 1
|
115 |
|
116 |
|
117 | |
118 |
|
119 |
|
120 |
|
121 |
|
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 |
|
134 | module.exports = MasterDataResource
|