Skip to content

Commit

Permalink
fix: add memory cache as default cache
Browse files Browse the repository at this point in the history
  • Loading branch information
SasanFarrokh committed Apr 20, 2019
1 parent 09d3ee5 commit 8ddbd1f
Show file tree
Hide file tree
Showing 18 changed files with 249 additions and 255 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
[![circle ci](https://img.shields.io/circleci/project/github/chimera-js/vue-chimera/master.svg?style=flat-square)](https://circleci.com/gh/chimera-js/vue-chimera)
[![npm version](https://img.shields.io/npm/v/vue-chimera.svg?style=flat-square)](https://www.npmjs.org/package/vue-chimera)
[![npm downloads](https://img.shields.io/npm/dt/vue-chimera.svg?style=flat-square)](http://npm-stat.com/charts.html?package=vue-chimera)
[![npm bundle size (minified + gzip)](https://img.shields.io/bundlephobia/minzip/vue-chimera.svg)](https://bundlephobia.com/result?p=vue-chimera@1.0.0)
[![npm bundle size (minified + gzip)](https://img.shields.io/bundlephobia/minzip/vue-chimera.svg)](https://bundlephobia.com/result?p=vue-chimera)
[![codecov](https://codecov.io/gh/SasanFarrokh/vue-chimera/branch/master/graph/badge.svg)](https://codecov.io/gh/SasanFarrokh/vue-chimera)

VueJS RESTful client with reactive features.
Expand Down
93 changes: 31 additions & 62 deletions dist/vue-chimera.cjs.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,15 +105,15 @@ const EVENT_CANCEL = 'cancel';
const EVENT_LOADING = 'loading';
const EVENT_TIMEOUT = 'timeout';
class Resource {
static from(value, baseOptions = {}) {
static from(value, baseOptions = {}, id) {
if (value == null) throw new Error('Cannot create resource from `null`');

if (value instanceof Resource) {
return value;
}

if (typeof value === 'string') {
return new Resource(value, null, baseOptions);
return new Resource(id, value, null, baseOptions);
}

if (isPlainObject(value)) {
Expand All @@ -125,16 +125,16 @@ class Resource {

if (options.cache) {
if (!baseOptions.cache) throw new Error('Pre definition of cache should be on Chimera instance options');
if (typeof options.cache !== 'object') throw Error('Cache should be an object');
if (!isPlainObject(options.cache)) throw Error('Cache should be an object');
let cache = Object.create(baseOptions.cache);
options.cache = Object.assign(cache, options.cache);
}

return new Resource(url, method, Object.assign({}, baseOptions, options));
return new Resource(id, url, method, Object.assign({}, baseOptions, options));
}
}

constructor(url, method, options) {
constructor(id, url, method, options) {
options = options || {};
method = method ? method.toLowerCase() : 'get';

Expand Down Expand Up @@ -162,6 +162,7 @@ class Resource {
this._eventListeners = {};
this.keepData = !!options.keepData;
this.cache = options.cache;
this.id = id;
this.ssrPrefetched = false;
this.cacheHit = false;
this.prefetch = typeof options.prefetch === 'string' ? options.prefetch.toLowerCase() === method : Boolean(options.prefetch);
Expand Down Expand Up @@ -392,55 +393,26 @@ class NullResource extends Resource {

}

class WebStorageCache {
constructor(options) {
if (typeof window !== 'undefined') {
const store = String(options.store).replace(/[\s-]/g).toLowerCase();
this.storage = store === 'sessionstorage' ? window.sessionStorage : window.localStorage;
}

if (!this.storage) throw Error('LocalStorageCache: Local storage is not available.');
const storage = {};
class MemoryCache {
constructor(options = {}) {
this.storage = storage;
this.defaultExpiration = options.defaultExpiration || 60000;
}

getObjectStore() {
const store = this.storage.getItem('_chimera');
return store ? JSON.parse(store) : {};
}

setObjectStore(x) {
this.storage.setItem('_chimera', JSON.stringify(x));
}

clear() {
this.storage.removeItem('_chimera');
this.storage = {};
}
/**
*
* @param key Key for the cache
* @param value Value for cache persistence
* @param expiration Expiration time in milliseconds
*/


setItem(key, value, expiration) {
const store = this.getObjectStore();
store[key] = {
this.storage[key] = {
expiration: Date.now() + (expiration || this.defaultExpiration),
value
};
this.setObjectStore(store);
}
/**
* If Cache exists return the Parsed Value, If Not returns {null}
*
* @param key
*/


getItem(key) {
const store = this.getObjectStore();
let item = store[key];
let item = this.storage[key];

if (item && item.value && Date.now() <= item.expiration) {
return item.value;
Expand All @@ -451,13 +423,11 @@ class WebStorageCache {
}

removeItem(key) {
const store = this.getObjectStore();
delete store[key];
this.setObjectStore(store);
delete this.storage[key];
}

keys() {
return Object.keys(this.getObjectStore());
return Object.keys(this.storage);
}

length() {
Expand All @@ -467,18 +437,19 @@ class WebStorageCache {
}

class Cache {
static from(options, vm) {
static from(options) {
if (!options) return null;
let {
store
} = options;
return new Cache(vm, options.strategy || 'stale', store);

if (isPlainObject(options)) {
return new Cache(options.strategy || 'stale', options.store);
}

return new Cache('stale', options);
}

constructor(vm, strategy, store) {
constructor(strategy, store) {
this.strategy = strategy;
this.store = store;
this.vm = vm;
}

get(r) {
Expand All @@ -493,7 +464,7 @@ class Cache {

assignCache(r, value) {
if (!value) value = this.get(r);
const strategy = this.strategy;
const strategy = (r.cacheOptions || {}).strategy || this.strategy;

const assign = () => {
Object.assign(r, value);
Expand All @@ -520,14 +491,12 @@ class Cache {

getCacheKey(r) {
const hash = typeof window !== 'undefined' ? window.btoa : x => x;
return '$_chimera_' + this.vm._uid + hash([r.requestConfig.url, r.requestConfig.params, r.requestConfig.data, r.requestConfig.method].join('|'));
return '$_chimera_' + (r.id || 'r') + '_' + hash([r.requestConfig.url, r.requestConfig.params, r.requestConfig.data, r.requestConfig.method].join('|'));
}

set store(x) {
if (!x || typeof x !== 'object') {
this._store = new WebStorageCache({
store: x
});
this._store = new MemoryCache();
} else {
this._store = x;
}
Expand All @@ -547,7 +516,7 @@ class VueChimera {
this.axios = this.options.axios = !this.options.axios && this._vm.$axios ? this._vm.$axios : createAxios(this.options.axios);

if (this.options.cache) {
this.cache = this.options.cache = Cache.from(this.options.cache, this._vm);
this.cache = this.options.cache = Cache.from(this.options.cache);
}

const vmOptions = this._vm.$options;
Expand All @@ -556,7 +525,7 @@ class VueChimera {
resources = Object.assign({}, resources);

for (let key in resources) {
if (key.charAt(0) === '$' || !resources.hasOwnProperty(key)) continue;
if (!resources.hasOwnProperty(key) || key.charAt(0) === '$') continue;
let r = resources[key];

if (typeof r === 'function') {
Expand All @@ -567,7 +536,7 @@ class VueChimera {

vmOptions.watch['$_chimera__' + key] = t => this.updateReactiveResource(key, t);
} else {
resources[key] = Resource.from(r, this.options);
resources[key] = Resource.from(r, this.options, key);
}

vmOptions.computed[key] = () => resources[key];
Expand All @@ -584,7 +553,7 @@ class VueChimera {
Object.defineProperty(resources, '$loading', {
get() {
for (let r in this) {
if (r.loading) return true;
if (this.hasOwnProperty(r) && r.loading) return true;
}

return false;
Expand All @@ -603,7 +572,7 @@ class VueChimera {
updateReactiveResource(key) {
const oldResource = this.resources[key];
oldResource.stopInterval();
let r = Resource.from(this._reactiveResources[key].call(this._vm), this.options); // Keep data
let r = Resource.from(this._reactiveResources[key].call(this._vm), this.options, key); // Keep data

if (oldResource.keepData) {
r._data = oldResource._data;
Expand Down
Loading

0 comments on commit 8ddbd1f

Please # to comment.