UNPKG

declastruct-stripe-sdk

Version:

declarative control of stripe constructs, via declastruct

59 lines 2.91 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getInvoice = void 0; const domain_objects_1 = require("domain-objects"); const helpful_errors_1 = require("helpful-errors"); const visualogic_1 = require("visualogic"); const DeclaredStripeInvoice_1 = require("../../domain/objects/DeclaredStripeInvoice"); const castToDeclaredStripeInvoice_1 = require("../cast/castToDeclaredStripeInvoice"); const getCustomer_1 = require("../customer/getCustomer"); exports.getInvoice = (0, visualogic_1.withLogTrail)(async (input, context) => { // handle by ref if (input.by.ref) return (0, domain_objects_1.isUniqueKeyRef)({ of: DeclaredStripeInvoice_1.DeclaredStripeInvoice })(input.by.ref) ? (0, exports.getInvoice)({ by: { unique: input.by.ref } }, context) : (0, exports.getInvoice)({ by: { primary: input.by.ref } }, context); // handle get by id if (input.by.primary) { try { const invoice = await context.stripe.invoices.retrieve(input.by.primary.id); if (invoice.deleted) return null; return (0, castToDeclaredStripeInvoice_1.castToDeclaredStripeInvoice)(invoice); } catch (error) { if (!(error instanceof Error)) throw error; if (error.message.includes('No such invoice')) return null; // handle "null" responses without an error throw error; } } // handle get by unique if (input.by.unique) { // lookup the customer by ref const customerFound = await (0, getCustomer_1.getCustomer)({ by: { ref: input.by.unique.customerRef } }, context); if (!customerFound) throw new helpful_errors_1.UnexpectedCodePathError('customer does not exist for by ref', { input, }); // lookup the invoices by customer, to filter down to a subset const { data: candidates } = await context.stripe.invoices.list({ customer: customerFound.id, limit: 100, }); // now find the one with this exid, for the customer const targets = candidates.filter((candidate) => candidate.metadata?.exid === input.by.unique?.exid); const [target, ...otherOptions] = targets.filter((thisOption) => thisOption.status !== 'void'); if (otherOptions.length) throw new helpful_errors_1.UnexpectedCodePathError('more than one invoice matches the .unique key', { input, matches: targets }); if (!target) return null; return (0, castToDeclaredStripeInvoice_1.castToDeclaredStripeInvoice)(target); } // otherwise, unexpected input throw new helpful_errors_1.UnexpectedCodePathError('invalid input', { input }); }, { name: (0, visualogic_1.getResourceNameFromFileName)(__filename), }); //# sourceMappingURL=getInvoice.js.map