Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions app/adapters/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,24 @@ import { inject as service } from '@ember/service';

export default RESTAdapter.extend({
fastboot: service(),
fetcher: service(),

namespace: 'api/v1',

ajax(url, type, options) {
if (type === 'GET') {
let cache = this.fetcher.get(url, options);
if (cache) {
return cache;
}
}

return this._super(url, type, options).then(resp => {
this.fetcher.put(url, options, resp);
return resp;
});
},

headers: computed('fastboot.{isFastBoot,request.headers}', function () {
if (this.fastboot.isFastBoot) {
return { 'User-Agent': this.fastboot.request.headers.get('User-Agent') };
Expand Down
42 changes: 31 additions & 11 deletions app/services/fetcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,51 @@ import Service, { inject as service } from '@ember/service';

import ajax from '../utils/ajax';

const KEY = 'ajax-cache';

export default class FetcherService extends Service {
@service fastboot;

ajax(url) {
get(url, options) {
let shoebox = this.fastboot.shoebox;
if (!shoebox) {
return;
}
let cache = shoebox.retrieve(KEY) || {};
let key = cacheKey(url, options);
return cache[key];
}

put(url, options, obj) {
let fastboot = this.fastboot;
let shoebox = this.fastboot.shoebox;
let cache = shoebox.retrieve('ajax-cache');
if (!cache) {
cache = {};
if (!(shoebox && fastboot.isFastBoot)) {
return;
}

if (cache[url]) {
return cache[url];
let cache = shoebox.retrieve(KEY) || {};
let key = cacheKey(url, options);
cache[key] = deepCopy(obj);
shoebox.put(KEY, cache);
}

ajax(url) {
let resp = this.get(url);
if (resp) {
return resp;
}

return ajax(url).then(function (resp) {
if (shoebox && fastboot.isFastBoot) {
cache[url] = deepCopy(resp);
shoebox.put('ajax-cache', cache);
}
return ajax(url).then(resp => {
this.put(url, resp);
return resp;
});
}
}

function cacheKey(url, options) {
return url + JSON.stringify(options);
}

function deepCopy(obj) {
return JSON.parse(JSON.stringify(obj));
}