Skip to content

Commit 2397c53

Browse files
kzysTurbo87
authored andcommitted
Don't make duplicated requests through Ember Data
This will prevent duplicated requests on `/crates` and other Ember Data-powered pages.
1 parent 14b0db1 commit 2397c53

File tree

2 files changed

+40
-11
lines changed

2 files changed

+40
-11
lines changed

app/adapters/application.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,24 @@ import { inject as service } from '@ember/service';
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

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,40 @@ import Service, { inject as service } from '@ember/service';
22

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

5+
const KEY = 'ajax-cache';
6+
57
export default class FetcherService extends Service {
68
@service fastboot;
79

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

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

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

0 commit comments

Comments
 (0)