-
Notifications
You must be signed in to change notification settings - Fork 1.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
ModelSync.Local implementation (final) - passing on A-grade browsers #1218
Changes from 13 commits
fde1bb7
ea0cbb4
4696889
e3db128
3a2edf1
8de47e0
610c3ff
23a328c
7e11148
c5e9fc1
ec63520
19720b7
67bb51c
63df36e
370e88d
fa961ad
2797cd8
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,299 @@ | ||
/* | ||
An extension which provides a sync implementation through locally stored | ||
key value pairs, either through the HTML localStorage API or falling back | ||
onto an in-memory cache, that can be mixed into a Model or ModelList subclass. | ||
|
||
@module app | ||
@submodule model-sync-local | ||
@since @VERSION@ | ||
**/ | ||
|
||
/** | ||
An extension which provides a sync implementation through locally stored | ||
key value pairs, either through the HTML localStorage API or falling back | ||
onto an in-memory cache, that can be mixed into a Model or ModelList subclass. | ||
|
||
A group of Models/ModelLists is serialized in localStorage by either its | ||
class name, or a specified 'root' that is provided. | ||
|
||
var User = Y.Base.create('user', Y.Model, [Y.ModelSync.Local], { | ||
root: 'user' | ||
}); | ||
|
||
var Users = Y.Base.create('users', Y.ModelList, [Y.ModelSync.Local], { | ||
model: User, | ||
}); | ||
|
||
@class ModelSync.Local | ||
@extensionfor Model | ||
@extensionfor ModelList | ||
@since @VERSION@ | ||
**/ | ||
function LocalSync() {} | ||
|
||
/** | ||
Properties that shouldn't be turned into ad-hoc attributes when passed to a | ||
Model or ModelList constructor. | ||
|
||
@property _NON_ATTRS_CFG | ||
@type Array | ||
@default ['root'] | ||
@static | ||
@protected | ||
@since @VERSION@ | ||
**/ | ||
LocalSync._NON_ATTRS_CFG = ['root']; | ||
|
||
/** | ||
Feature testing for `localStorage` availability. | ||
Will return falsey for browsers with `localStorage`, but that don't | ||
actually work, such as iOS Safari in private browsing mode. | ||
|
||
@property _hasLocalStorage | ||
@type Boolean | ||
@private | ||
**/ | ||
LocalSync._hasLocalStorage = (function () { | ||
var LS = Y.config.win.localStorage, | ||
test = Y.guid(); | ||
|
||
try { | ||
LS.setItem(test, test); | ||
LS.removeItem(test); | ||
return true | ||
} catch (e) { | ||
return false; | ||
} | ||
})(), | ||
|
||
/** | ||
Object of key/value pairs to fall back on when localStorage is not available. | ||
|
||
@property _data | ||
@type Object | ||
@private | ||
**/ | ||
LocalSync._data = {}; | ||
|
||
LocalSync.prototype = { | ||
|
||
// -- Public Methods ------------------------------------------------------- | ||
|
||
/** | ||
Root used as the key inside of localStorage and/or the in-memory store. | ||
|
||
@property root | ||
@type String | ||
@default "" | ||
@since @VERSION@ | ||
**/ | ||
root: '', | ||
|
||
/** | ||
Shortcut for access to localStorage. | ||
|
||
@property storage | ||
@type Storage | ||
@default null | ||
@since @VERSION@ | ||
**/ | ||
storage: null, | ||
|
||
// -- Lifecycle Methods ----------------------------------------------------- | ||
initializer: function (config) { | ||
var store; | ||
|
||
config || (config = {}); | ||
|
||
if ('root' in config) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I suppose this assumes a
seems more correct. Then again, since
suffices. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good point, but I think we need to check the prototype, since this is a mix-in for a Y.Base class. In that case, if something along the prototype chain has a There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I see. |
||
this.root = config.root || ''; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Since There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I guess this might protect against the case where someone actually does explicitly specify There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I like this pattern of coercing all falsy values to an empty string. This way the rest of the code can always assume |
||
} | ||
|
||
if (this.model && this.model.prototype.root) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can you add a code comment there that this is checking if the sync layer is being applied to a ModelList and if so, trying to look for a root on its |
||
this.root = this.model.prototype.root; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
} | ||
|
||
if (LocalSync._hasLocalStorage) { | ||
this.storage = Y.config.win.localStorage; | ||
store = this.storage.getItem(this.root); | ||
} else { | ||
Y.log("Could not access localStorage.", "warn"); | ||
} | ||
|
||
// Pull in existing data from localStorage, if possible. | ||
// Otherwise, see if there's existing data on the local cache. | ||
if (store) { | ||
LocalSync._data[this.root] = Y.JSON.parse(store); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do you want to |
||
} else { | ||
LocalSync._data[this.root] = (LocalSync._data[this.root] || {}); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Could use conditional assignment here and swap the Or use an |
||
} | ||
}, | ||
|
||
// -- Public Methods ----------------------------------------------------------- | ||
|
||
/** | ||
Creates a synchronization layer with the localStorage API, if available. | ||
Otherwise, falls back to a in-memory data store. | ||
|
||
This method is called internally by load(), save(), and destroy(). | ||
|
||
@method sync | ||
@param {String} action Sync action to perform. May be one of the following: | ||
|
||
* **create**: Store a newly-created model for the first time. | ||
* **read** : Load an existing model. | ||
* **update**: Update an existing model. | ||
* **delete**: Delete an existing model. | ||
|
||
@param {Object} [options] Sync options | ||
@param {callback} [callback] Called when the sync operation finishes. | ||
@param {Error|null} callback.err If an error occurred, this parameter will | ||
contain the error. If the sync operation succeeded, _err_ will be | ||
falsey. | ||
@param {Any} [callback.response] The response from our sync. This value will | ||
be passed to the parse() method, which is expected to parse it and | ||
return an attribute hash. | ||
**/ | ||
sync: function (action, options, callback) { | ||
options || (options = {}); | ||
var response, errorInfo; | ||
|
||
try { | ||
switch (action) { | ||
case 'read': | ||
if (this._isYUIModelList) { | ||
response = this._index(options); | ||
} else { | ||
response = this._show(options); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What about switching There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah, that was the main decision behind that. I could switch it to There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Either way it's fine, it's a protected helper method so since you explicitly called it |
||
} | ||
break; | ||
case 'create': | ||
response = this._create(options); | ||
break; | ||
case 'update': | ||
response = this._update(options); | ||
break; | ||
case 'delete': | ||
response = this._destroy(options); | ||
break; | ||
} | ||
} catch (error) { | ||
errorInfo = error.message; | ||
} | ||
|
||
if (response) { | ||
callback(null, response); | ||
} else if (errorInfo) { | ||
callback(errorInfo); | ||
} else { | ||
callback("Data not found in LocalStorage"); | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The above is logically equivalent to the following simplified version:
|
||
}, | ||
|
||
/** | ||
Generate a random GUID for our Models. This can be overriden if you have | ||
another method of generating different IDs. | ||
|
||
@method generateID | ||
@protected | ||
@param {String} pre Optional GUID prefix | ||
**/ | ||
generateID: function (pre) { | ||
return Y.guid(pre + '_'); | ||
}, | ||
|
||
// -- Protected Methods ---------------------------------------------------- | ||
|
||
/** | ||
Sync method correlating to the "read" operation, for a Model List | ||
|
||
@method _index | ||
@return {Object[]} Array of objects found for that root key | ||
@protected | ||
@since @VERSION@ | ||
**/ | ||
_index: function (options) { | ||
return Y.Object.values(LocalSync._data[this.root]); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is effectively saying that storage order is not significant for a model list's data. If we want to make it significant and consistent, then I don't want us to store it as an object whose key-order is not guaranteed, especially when going to/from JSON. |
||
}, | ||
|
||
/** | ||
Sync method correlating to the "read" operation, for a Model | ||
|
||
@method _show | ||
@return {Object} Object found for that root key and model ID | ||
@protected | ||
@since @VERSION@ | ||
**/ | ||
_show: function (options) { | ||
return LocalSync._data[this.root][this.get('id')]; | ||
}, | ||
|
||
/** | ||
Sync method correlating to the "create" operation | ||
|
||
@method _show | ||
@return {Object} The new object created. | ||
@protected | ||
@since @VERSION@ | ||
**/ | ||
_create: function (options) { | ||
var hash = this.toJSON(); | ||
hash.id = this.generateID(this.root); | ||
LocalSync._data[this.root][hash.id] = hash; | ||
|
||
this._save(); | ||
return hash; | ||
}, | ||
|
||
/** | ||
Sync method correlating to the "update" operation | ||
|
||
@method _update | ||
@return {Object} The updated object. | ||
@protected | ||
@since @VERSION@ | ||
**/ | ||
_update: function (options) { | ||
var hash = Y.merge(this.toJSON(), options); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why are you merging in the |
||
LocalSync._data[this.root][this.get('id')] = hash; | ||
|
||
this._save(); | ||
return hash; | ||
}, | ||
|
||
/** | ||
Sync method correlating to the "delete" operation. Deletes the data | ||
from the in-memory object, and saves into localStorage if available. | ||
|
||
@method _destroy | ||
@return {Object} The deleted object. | ||
@protected | ||
@since @VERSION@ | ||
**/ | ||
_destroy: function (options) { | ||
delete LocalSync._data[this.root][this.get('id')]; | ||
this._save(); | ||
return this.toJSON(); | ||
}, | ||
|
||
/** | ||
Saves the current in-memory store into a localStorage key/value pair | ||
if localStorage is available; otherwise, does nothing. | ||
|
||
@method _save | ||
@protected | ||
@since @VERSION@ | ||
**/ | ||
_save: function () { | ||
if (LocalSync._hasLocalStorage) { | ||
this.storage && this.storage.setItem( | ||
this.root, | ||
Y.JSON.stringify(LocalSync._data[this.root]) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm curious to know why you're serializing all the objects under this root on every save, instead of only serializing the one model or the entire list on save. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
You could serialize all of the objects into individual key/value pairs, but that would be less performant once you have to access all of the objects at once, which is a pretty common use case. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Okay cool, seems like the right tradeoff to keep the state for the whole What's happens when there's several classes and instances that use the same |
||
); | ||
} | ||
} | ||
}; | ||
|
||
// -- Namespace --------------------------------------------------------------- | ||
|
||
Y.namespace('ModelSync').Local = LocalSync; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Perhaps we should advocate the use of feature testing, rather than simply detecting whether
localStorage
exists or not. For example, we should test if we're actually able to set and remove items fromlocalStorage
, like so:The main reason being there are times when
localStorage
is detected, but is actually unusable. For example, when browsing in private mode on an iOS device,localStorage
is available but cannot be used.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This sounds good to me, I'll push this up in just a bit.