This repository has been archived by the owner on Apr 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 109
/
backbone.dualstorage.coffee
303 lines (250 loc) · 9.42 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
###
Backbone dualStorage Adapter v1.0.1
A simple module to replace `Backbone.sync` with *localStorage*-based
persistence. Models are given GUIDS, and saved into a JSON object. Simple
as that.
###
# Make it easy for collections to sync dirty and destroyed records
# Simply call collection.syncDirtyAndDestroyed()
Backbone.Collection.prototype.syncDirty = ->
url = result(@, 'url')
store = localStorage.getItem "#{url}_dirty"
ids = (store and store.split(',')) or []
for id in ids
model = if id.length == 36 then @where(id: id)[0] else @get(id)
model.save()
Backbone.Collection.prototype.syncDestroyed = ->
url = result(@, 'url')
store = localStorage.getItem "#{url}_destroyed"
ids = (store and store.split(',')) or []
for id in ids
model = new @model({id: id})
model.collection = @
model.destroy()
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 (hopefully)-unique GUID, if it doesn't already
# have an id of it's own.
create: (model) ->
if not _.isObject(model) then return model
#if model.attributes? then model = model.attributes #removed to fix issue 14
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) ->
JSON.parse localStorage.getItem(@name + @sep + model.id)
# 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) ->
store = new Store options.storeName
response = switch method
when 'read'
if model.id
store.find(model)
else
store.findAll()
when 'hasDirtyOrDestroyed'
store.hasDirtyOrDestroyed()
when 'clear'
store.clear()
when 'create'
unless options.add and not options.merge and (preExisting = store.find(model))
model = store.create(model)
store.dirty(model) if options.dirty
model
else
preExisting
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)
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 = result(model.collection, 'url') || result(model, 'url')
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)
localsync('clear', model, options) unless options.add
if _.isArray resp
for i in resp
localsync('create', i, options)
else
localsync('create', resp, options)
success(resp, status, xhr)
options.error = (resp) ->
success localsync(method, model, options)
onlineSync(method, model, options)
when 'create'
options.success = (resp, status, xhr) ->
localsync(method, resp, options)
success(resp, status, xhr)
options.error = (resp) ->
options.dirty = true
success localsync(method, model, options)
onlineSync(method, model, options)
when 'update'
if _.isString(model.id) and model.id.length == 36
originalModel = model.clone()
options.success = (resp, status, xhr) ->
localsync('delete', originalModel, options)
localsync('create', resp, options)
success(resp, status, xhr)
options.error = (resp) ->
options.dirty = true
success localsync(method, originalModel, options)
model.set id: null
onlineSync('create', model, options)
else
options.success = (resp, status, xhr) ->
updatedAttributes = _.extend({}, model.toJSON(), resp)
localsync(method, updatedAttributes, options)
success(resp, status, xhr)
options.error = (resp) ->
options.dirty = true
success localsync(method, model, options)
onlineSync(method, model, options)
when 'delete'
if _.isString(model.id) and model.id.length == 36
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