Skip to content

Instantly share code, notes, and snippets.

@Ravenstine
Last active March 13, 2018 04:48
Show Gist options
  • Save Ravenstine/44b5cb687f263ec8f08c23eabe262536 to your computer and use it in GitHub Desktop.
Save Ravenstine/44b5cb687f263ec8f08c23eabe262536 to your computer and use it in GitHub Desktop.
Ember Fastboot Shoebox Mixin
// app/mixins/shoebox.js
import Ember from 'ember';
import fetch from 'fetch';
const {
Mixin,
RSVP: {Promise},
inject: {service}
} = Ember;
function generateFakeResponse(obj) {
return Promise.resolve({
status: obj.status,
json: function() { return Promise.resolve(obj.json); }
});
}
export default Mixin.create({
fastboot: service(),
shoebox: service(),
fetch(...args) {
let requestToken = this.get('shoebox').tokenizeAjaxRequest(...args);
if(this.get('fastboot.isFastBoot')) {
return fetch(...arguments)
.then(resp => resp.json())
.then(json => {
let serialized = {
status: resp.status,
json: json
}
this.get('shoebox').pushResponse(requestToken, serialized);
return generateFakeResponse(serialized);
});
}
let cachedResponse = this.get('shoebox').popResponse(requestToken);
if(cachedResponse) return generateFakeResponse(cachedResponse);
return fetch(...arguments);
}
});
// app/services/shoebox.js
import Ember from 'ember';
import md5 from 'npm:blueimp-md5';
const {
Service,
inject: {service},
$
} = Ember;
export default Service.extend({
fastboot: service(),
pushResponse(requestToken, response) {
this.get('fastboot.shoebox').put(
requestToken,
JSON.stringify(response)
)
return response
},
popResponse(requestToken) {
let response = this.get('fastboot.shoebox').retrieve(requestToken);
this.eraseResponse(requestToken);
return response ? JSON.parse(response) : response;
},
eraseResponse(requestToken) {
$(`#shoebox-${requestToken}`).remove();
this.set(`fastboot.shoebox.${requestToken}`, undefined);
},
tokenizeAjaxRequest(url, options = {}) {
return md5(`${url}---${JSON.stringify(options)}`)
.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment