diff --git a/app/adapters/application.js b/app/adapters/application.js index ab51264c6d6..dc9c3188d1c 100644 --- a/app/adapters/application.js +++ b/app/adapters/application.js @@ -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') }; diff --git a/app/services/fetcher.js b/app/services/fetcher.js index ca43935318f..5e0940c789f 100644 --- a/app/services/fetcher.js +++ b/app/services/fetcher.js @@ -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)); }