Skip to content

Commit a369d6e

Browse files
committed
Don't make duplicated requests through Ember Data
This will prevent duplicated requests on `/crates` and other Ember Data-powered pages.
1 parent d46b4e3 commit a369d6e

File tree

2 files changed

+40
-11
lines changed

2 files changed

+40
-11
lines changed

app/adapters/application.js

+15
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,24 @@ import { computed } from '@ember/object';
44

55
export default RESTAdapter.extend({
66
fastboot: service(),
7+
fetcher: service(),
78

89
namespace: 'api/v1',
910

11+
ajax: function(url, type, options) {
12+
if (type === 'GET') {
13+
let cache = this.fetcher.get(url);
14+
if (cache) {
15+
return cache;
16+
}
17+
}
18+
19+
return this._super(url, type, options).then(resp => {
20+
this.fetcher.put(url, resp);
21+
return resp;
22+
});
23+
},
24+
1025
headers: computed('fastboot.{isFastBoot,request.headers}', function() {
1126
if (this.fastboot.isFastBoot) {
1227
return { 'User-Agent': this.fastboot.request.headers.get('User-Agent') };

app/services/fetcher.js

+25-11
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,40 @@
11
import Service, { inject as service } from '@ember/service';
22
import ajax from 'ember-fetch/ajax';
33

4+
const KEY = 'ajax-cache';
5+
46
export default Service.extend({
57
fastboot: service(),
68

7-
ajax(url) {
9+
get(url) {
10+
let shoebox = this.fastboot.shoebox;
11+
if (!shoebox) {
12+
return;
13+
}
14+
let cache = shoebox.retrieve(KEY) || {};
15+
return cache[url];
16+
},
17+
18+
put(url, obj) {
819
let fastboot = this.fastboot;
920
let shoebox = this.fastboot.shoebox;
10-
let cache = shoebox.retrieve('ajax-cache');
11-
if (!cache) {
12-
cache = {};
21+
if (!(shoebox && fastboot.isFastBoot)) {
22+
return;
1323
}
1424

15-
if (cache[url]) {
16-
return cache[url];
25+
let cache = shoebox.retrieve(KEY) || {};
26+
cache[url] = deepCopy(obj);
27+
shoebox.put(KEY, cache);
28+
},
29+
30+
ajax(url) {
31+
let resp = this.get(url);
32+
if (resp) {
33+
return resp;
1734
}
1835

19-
return ajax(url).then(function(resp) {
20-
if (shoebox && fastboot.isFastBoot) {
21-
cache[url] = deepCopy(resp);
22-
shoebox.put('ajax-cache', cache);
23-
}
36+
return ajax(url).then(resp => {
37+
this.put(url, resp);
2438
return resp;
2539
});
2640
},

0 commit comments

Comments
 (0)