Advanced Query Cache
import Ember from 'ember'; | |
export default Ember.Controller.extend({ | |
appName: 'Ember Twiddle' | |
}); |
import Ember from 'ember'; | |
const { | |
ArrayProxy, | |
get, | |
Service, | |
inject | |
} = Ember; | |
/* | |
Can't trust JSON.stringify() to be consistent | |
This also isn't quite right but it's close. | |
*/ | |
function stringify(obj, _isTop = true) { | |
if (!obj) { | |
return _isTop ? '-all' : 'null'; | |
} | |
const keys = Object.keys(options); | |
let key = ''; | |
keys.sort(); | |
for (let i = 0; i < keys.length; i++) { | |
let value = keys[i]; | |
if (typeof value !== 'string') { | |
value = stringify(value, false); | |
} | |
key += value; | |
} | |
return key; | |
} | |
export default Service.extend({ | |
store: inject.service(), | |
query(type, options) { | |
let key = `-q${type}:${stringify(options)}`; | |
if (!this._cache[key]) { | |
this._cache[key] = this.get('store').query(type, options); | |
} | |
return this._cache[key]; | |
}, | |
queryRecord(type, options) { | |
let key = `-qOne${type}:${stringify(options)}`; | |
if (!this._cache[key]) { | |
this._cache[key] = this.get('store').queryRecord(type, options); | |
} | |
return this._cache[key]; | |
}, | |
queryLive(type, options) { | |
return this.query(type, options) | |
.then((r) => { | |
const meta = get(r, 'meta'); | |
const content = this.get('store').peekAll(type); | |
const proxy = ArrayProxy.create({ content, meta }); | |
return proxy; | |
}); | |
}, | |
init() { | |
this._super(); | |
this._cache = Object.create(null); | |
} | |
}); |
{ | |
"version": "0.12.1", | |
"EmberENV": { | |
"FEATURES": {} | |
}, | |
"options": { | |
"use_pods": false, | |
"enable-testing": false | |
}, | |
"dependencies": { | |
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js", | |
"ember": "2.12.0", | |
"ember-template-compiler": "2.12.0", | |
"ember-testing": "2.12.0" | |
}, | |
"addons": { | |
"ember-data": "2.12.1" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment