mirror of
https://github.com/TryGhost/Ghost.git
synced 2024-12-27 04:43:12 +03:00
117309b4e8
no-issue Using models internally and in the exported API means that we avoid expensive `toJSON` calls, which affects performance when looping through large lists of members. It also allows us to take advantage of the new relations used in the models. The addition of "ByID" methods for linking stripe customers and setting complimentary subscriptions allows bulk imports to avoid the overhead of creating a model for each members, instead passing an id string. n.b. currently the impl _does_ still create models, but it makes it easier to optimise and refactor in the future.
71 lines
1.8 KiB
JavaScript
71 lines
1.8 KiB
JavaScript
module.exports = function ({
|
|
Member,
|
|
StripeWebhook,
|
|
StripeCustomer,
|
|
StripeCustomerSubscription
|
|
}) {
|
|
async function setMetadata(module, metadata) {
|
|
if (module !== 'stripe') {
|
|
return;
|
|
}
|
|
|
|
if (metadata.customer) {
|
|
const member = await Member.findOne({
|
|
id: metadata.customer.member_id
|
|
});
|
|
|
|
if (member) {
|
|
await StripeCustomer.upsert(metadata.customer, {
|
|
customer_id: metadata.customer.customer_id
|
|
});
|
|
}
|
|
}
|
|
|
|
if (metadata.subscription) {
|
|
const customer = await StripeCustomer.findOne({
|
|
customer_id: metadata.subscription.customer_id
|
|
});
|
|
if (customer) {
|
|
await StripeCustomerSubscription.upsert(metadata.subscription, {
|
|
subscription_id: metadata.subscription.subscription_id
|
|
});
|
|
}
|
|
}
|
|
|
|
if (metadata.webhook) {
|
|
await StripeWebhook.upsert(metadata.webhook, {
|
|
webhook_id: metadata.webhook.webhook_id
|
|
});
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
async function getMetadata(module, member) {
|
|
if (module !== 'stripe') {
|
|
return;
|
|
}
|
|
|
|
if (!member.relations.stripeCustomers) {
|
|
await member.load(['stripeCustomers']);
|
|
}
|
|
|
|
if (!member.relations.stripeSubscriptions) {
|
|
await member.load(['stripeSubscriptions', 'stripeSubscriptions.customer']);
|
|
}
|
|
|
|
const customers = member.related('stripeCustomers').toJSON();
|
|
const subscriptions = member.related('stripeSubscriptions').toJSON();
|
|
|
|
return {
|
|
customers: customers,
|
|
subscriptions: subscriptions
|
|
};
|
|
}
|
|
|
|
return {
|
|
setMetadata,
|
|
getMetadata
|
|
};
|
|
};
|