Ghost/ghost/admin/app/components/gh-billing-iframe.js
Aileen Nowak e20e5775a6 Fixed requesting subscription before sending token
no issue

- The Ghost(Pro) billing app would request a token once mounted to which Ghost sends the response to
- Before, we wouldn't wait for the token to be sent and request subscription information from the Ghost(Pro) app straight away, which resulted in another token request (because it's not there yet)
- This change will wait for the token to be sent before requesting subscription information from the Ghost(Pro) app to avoid duplicated requests to our servers
2021-05-20 17:10:10 +12:00

45 lines
1.7 KiB
JavaScript

import Component from '@ember/component';
import {inject as service} from '@ember/service';
export default Component.extend({
billing: service(),
config: service(),
ghostPaths: service(),
ajax: service(),
didInsertElement() {
let fetchingSubscription = false;
this.billing.getBillingIframe().src = this.billing.getIframeURL();
window.addEventListener('message', (event) => {
let token;
if (event && event.data && event.data.request === 'token') {
const ghostIdentityUrl = this.get('ghostPaths.url').api('identities');
this.ajax.request(ghostIdentityUrl).then((response) => {
token = response && response.identities && response.identities[0] && response.identities[0].token;
this.billing.getBillingIframe().contentWindow.postMessage({
request: 'token',
response: token
}, '*');
});
// NOTE: the handler is placed here to avoid additional logic to check if iframe has loaded
// receiving a 'token' request is an indication that page is ready
if (!fetchingSubscription && !this.billing.get('subscription') && token) {
fetchingSubscription = true;
this.billing.getBillingIframe().contentWindow.postMessage({
query: 'getSubscription',
response: 'subscription'
}, '*');
}
}
if (event && event.data && event.data.subscription) {
this.billing.set('subscription', event.data.subscription);
}
});
}
});