forked from nilbus/Backbone.dualStorage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backbone.dualstorage.coffee
347 lines (287 loc) · 11.2 KB
/
backbone.dualstorage.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
###
Backbone dualStorage Adapter v1.2.0
A simple module to replace `Backbone.sync` with *localStorage*-based
persistence. Models are given GUIDS, and saved into a JSON object. Simple
as that.
###
Backbone.Model.prototype.hasTempId = ->
_.isString(@id) and @id.length is 36
getStoreName = (collection, model) ->
model ||= collection.model.prototype
result(collection, 'storeName') || result(model, 'storeName') ||
result(collection, 'url') || result(model, 'urlRoot') || result(model, 'url')
# Make it easy for collections to sync dirty and destroyed records
# Simply call collection.syncDirtyAndDestroyed()
Backbone.Collection.prototype.syncDirty = ->
store = localStorage.getItem("#{getStoreName(@)}_dirty")
ids = (store and store.split(',')) or []
for id in ids
@get(id)?.save()
Backbone.Collection.prototype.dirtyModels = ->
store = localStorage.getItem("#{getStoreName(@)}_dirty")
ids = (store and store.split(',')) or []
models = for id in ids
@get(id)
_(models).compact()
Backbone.Collection.prototype.syncDestroyed = ->
store = localStorage.getItem("#{getStoreName(@)}_destroyed")
ids = (store and store.split(',')) or []
for id in ids
model = new @model
model.id = id
model.collection = @
model.destroy()
Backbone.Collection.prototype.destroyedModelIds = ->
store = localStorage.getItem("#{getStoreName(@)}_destroyed")
ids = (store and store.split(',')) or []
Backbone.Collection.prototype.syncDirtyAndDestroyed = ->
@syncDirty()
@syncDestroyed()
# Generate four random hex digits.
S4 = ->
(((1 + Math.random()) * 0x10000) | 0).toString(16).substring 1
# Our Store is represented by a single JS object in *localStorage*. Create it
# with a meaningful name, like the name you'd give a table.
class window.Store
sep: '' # previously '-'
constructor: (name) ->
@name = name
@records = @recordsOn @name
# Generates an unique id to use when saving new instances into localstorage
# by default generates a pseudo-GUID by concatenating random hexadecimal.
# you can overwrite this function to use another strategy
generateId: ->
S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4()
# Save the current state of the **Store** to *localStorage*.
save: ->
localStorage.setItem @name, @records.join(',')
recordsOn: (key) ->
store = localStorage.getItem(key)
(store and store.split(',')) or []
dirty: (model) ->
dirtyRecords = @recordsOn @name + '_dirty'
if not _.include(dirtyRecords, model.id.toString())
dirtyRecords.push model.id
localStorage.setItem @name + '_dirty', dirtyRecords.join(',')
model
clean: (model, from) ->
store = "#{@name}_#{from}"
dirtyRecords = @recordsOn store
if _.include dirtyRecords, model.id.toString()
localStorage.setItem store, _.without(dirtyRecords, model.id.toString()).join(',')
model
destroyed: (model) ->
destroyedRecords = @recordsOn @name + '_destroyed'
if not _.include destroyedRecords, model.id.toString()
destroyedRecords.push model.id
localStorage.setItem @name + '_destroyed', destroyedRecords.join(',')
model
# Add a model, giving it a unique GUID, if it doesn't already
# have an id of it's own.
create: (model) ->
if not _.isObject(model) then return model
if not model.id
model.id = @generateId()
model.set model.idAttribute, model.id
localStorage.setItem @name + @sep + model.id, JSON.stringify(model)
@records.push model.id.toString()
@save()
model
# Update a model by replacing its copy in `this.data`.
update: (model) ->
localStorage.setItem @name + @sep + model.id, JSON.stringify(model)
if not _.include(@records, model.id.toString())
@records.push model.id.toString()
@save()
model
clear: ->
for id in @records
localStorage.removeItem @name + @sep + id
@records = []
@save()
hasDirtyOrDestroyed: ->
not _.isEmpty(localStorage.getItem(@name + '_dirty')) or not _.isEmpty(localStorage.getItem(@name + '_destroyed'))
# Retrieve a model from `this.data` by id.
find: (model) ->
modelAsJson = localStorage.getItem(@name + @sep + model.id)
return null if modelAsJson == null
JSON.parse modelAsJson
# Return the array of all models currently in storage.
findAll: ->
for id in @records
JSON.parse localStorage.getItem(@name + @sep + id)
# Delete a model from `this.data`, returning it.
destroy: (model) ->
localStorage.removeItem @name + @sep + model.id
@records = _.reject(@records, (record_id) ->
record_id is model.id.toString()
)
@save()
model
callbackTranslator =
needsTranslation: Backbone.VERSION == '0.9.10'
forBackboneCaller: (callback) ->
if @needsTranslation
(model, resp, options) -> callback.call null, resp
else
callback
forDualstorageCaller: (callback, model, options) ->
if @needsTranslation
(resp) -> callback.call null, model, resp, options
else
callback
# Override `Backbone.sync` to use delegate to the model or collection's
# *localStorage* property, which should be an instance of `Store`.
localsync = (method, model, options) ->
isValidModel = (method is 'clear') or (method is 'hasDirtyOrDestroyed')
isValidModel ||= model instanceof Backbone.Model
isValidModel ||= model instanceof Backbone.Collection
if not isValidModel
throw new Error 'model parameter is required to be a backbone model or collection.'
store = new Store options.storeName
response = switch method
when 'read'
if model instanceof Backbone.Model
store.find(model)
else
store.findAll()
when 'hasDirtyOrDestroyed'
store.hasDirtyOrDestroyed()
when 'clear'
store.clear()
when 'create'
if options.add and not options.merge and (preExisting = store.find(model))
preExisting
else
model = store.create(model)
store.dirty(model) if options.dirty
model
when 'update'
store.update(model)
if options.dirty
store.dirty(model)
else
store.clean(model, 'dirty')
when 'delete'
store.destroy(model)
if options.dirty
store.destroyed(model)
else
if model.id.toString().length == 36
store.clean(model, 'dirty')
else
store.clean(model, 'destroyed')
response = response.attributes if response?.attributes
unless options.ignoreCallbacks
if response
options.success response
else
options.error 'Record not found'
response
# If the value of the named property is a function then invoke it;
# otherwise, return it.
# based on _.result from underscore github
result = (object, property) ->
return null unless object
value = object[property]
if _.isFunction(value) then value.call(object) else value
# Helper function to run parseBeforeLocalSave() in order to
# parse a remote JSON response before caching locally
parseRemoteResponse = (object, response) ->
if not (object and object.parseBeforeLocalSave) then return response
if _.isFunction(object.parseBeforeLocalSave) then object.parseBeforeLocalSave(response)
modelUpdatedWithResponse = (model, response) ->
modelClone = new Backbone.Model
modelClone.idAttribute = model.idAttribute
modelClone.set model.attributes
modelClone.set modelClone.parse response
modelClone
backboneSync = Backbone.sync
onlineSync = (method, model, options) ->
options.success = callbackTranslator.forBackboneCaller(options.success)
options.error = callbackTranslator.forBackboneCaller(options.error)
backboneSync(method, model, options)
dualsync = (method, model, options) ->
options.storeName = getStoreName(model.collection, model)
options.success = callbackTranslator.forDualstorageCaller(options.success, model, options)
options.error = callbackTranslator.forDualstorageCaller(options.error, model, options)
# execute only online sync
return onlineSync(method, model, options) if result(model, 'remote') or result(model.collection, 'remote')
# execute only local sync
local = result(model, 'local') or result(model.collection, 'local')
options.dirty = options.remote is false and not local
return localsync(method, model, options) if options.remote is false or local
# execute dual sync
options.ignoreCallbacks = true
success = options.success
error = options.error
switch method
when 'read'
if localsync('hasDirtyOrDestroyed', model, options)
success localsync(method, model, options)
else
options.success = (resp, status, xhr) ->
resp = parseRemoteResponse(model, resp)
if model instanceof Backbone.Collection
collection = model
idAttribute = collection.model.prototype.idAttribute
localsync('clear', collection, options) unless options.add
for modelAttributes in resp
model = collection.get(modelAttributes[idAttribute])
if model
responseModel = modelUpdatedWithResponse(model, modelAttributes)
else
responseModel = new collection.model(modelAttributes)
localsync('update', responseModel, options)
else
responseModel = modelUpdatedWithResponse(model, resp)
localsync('update', responseModel, options)
success(resp, status, xhr)
options.error = (resp) ->
success localsync(method, model, options)
onlineSync(method, model, options)
when 'create'
options.success = (resp, status, xhr) ->
updatedModel = modelUpdatedWithResponse model, resp
localsync(method, updatedModel, options)
success(resp, status, xhr)
options.error = (resp) ->
options.dirty = true
success localsync(method, model, options)
onlineSync(method, model, options)
when 'update'
if model.hasTempId()
temporaryId = model.id
options.success = (resp, status, xhr) ->
updatedModel = modelUpdatedWithResponse model, resp
model.set model.idAttribute, temporaryId, silent: true
localsync('delete', model, options)
localsync('create', updatedModel, options)
success(resp, status, xhr)
options.error = (resp) ->
options.dirty = true
model.set model.idAttribute, temporaryId, silent: true
success localsync(method, model, options)
model.set model.idAttribute, null, silent: true
onlineSync('create', model, options)
else
options.success = (resp, status, xhr) ->
updatedModel = modelUpdatedWithResponse model, resp
localsync(method, updatedModel, options)
success(resp, status, xhr)
options.error = (resp) ->
options.dirty = true
success localsync(method, model, options)
onlineSync(method, model, options)
when 'delete'
if model.hasTempId()
localsync(method, model, options)
else
options.success = (resp, status, xhr) ->
localsync(method, model, options)
success(resp, status, xhr)
options.error = (resp) ->
options.dirty = true
success localsync(method, model, options)
onlineSync(method, model, options)
Backbone.sync = dualsync