Created
May 2, 2019 18:12
-
-
Save Ravenstine/da939445c269bc69abb15a2e9aa3b007 to your computer and use it in GitHub Desktop.
Ember Shoebox
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// app/adapters/application.js | |
import DS from 'ember-data'; | |
import { inject as service } from '@ember-decorators/service'; | |
const { RESTAdapter } = DS; | |
export default class ApplicationAdapter extends RESTAdapter { | |
@service fastboot; | |
@service shoebox; | |
async ajax() { | |
let requestToken = this.shoebox.tokenizeAjaxRequest(...arguments); | |
if(!this.get('fastboot.isFastBoot')) { | |
const cachedResponse = this.shoebox.popResponse(requestToken); | |
if(cachedResponse) return cachedResponse; | |
return super.ajax(...arguments); | |
} | |
const resp = await super.ajax(...arguments); | |
this.shoebox.pushResponse(requestToken, resp); | |
return resp; | |
} | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// app/services/shoebox.js | |
import Service from '@ember/service'; | |
import { inject as service } from '@ember-decorators/service'; | |
import md5 from 'blueimp-md5'; | |
export default class ShoeboxService extends Service { | |
@service fastboot; | |
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) { | |
const element = document.querySelector(`#shoebox-${requestToken}`); | |
element.parentNode.removeChild(element); | |
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