UNPKG

declastruct-stripe-sdk

Version:

declarative control of stripe constructs, via declastruct

72 lines 3.39 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getInvoiceItem = void 0; const domain_objects_1 = require("domain-objects"); const helpful_errors_1 = require("helpful-errors"); const visualogic_1 = require("visualogic"); const DeclaredStripeInvoiceItem_1 = require("../../domain/objects/DeclaredStripeInvoiceItem"); const castToDeclaredStripeInvoiceItem_1 = require("../cast/castToDeclaredStripeInvoiceItem"); const getInvoice_1 = require("../invoice/getInvoice"); /** * .what = gets an invoice item from stripe */ exports.getInvoiceItem = (0, visualogic_1.withLogTrail)(async (input, context) => { // handle by ref if (input.by.ref) return (0, domain_objects_1.isUniqueKeyRef)({ of: DeclaredStripeInvoiceItem_1.DeclaredStripeInvoiceItem })(input.by.ref) ? (0, exports.getInvoiceItem)({ by: { unique: input.by.ref } }, context) : (0, exports.getInvoiceItem)({ by: { primary: input.by.ref } }, context); // handle get by id if (input.by.primary) { try { const item = await context.stripe.invoiceItems.retrieve(input.by.primary.id, { expand: ['price', 'discounts'], // required to cast to declared item }); if (item.deleted) return null; return (0, castToDeclaredStripeInvoiceItem_1.castToDeclaredStripeInvoiceItem)(item); } catch (error) { if (!(error instanceof Error)) throw error; if (error.message.includes('No such customer')) return null; // handle "null" responses without an error throw error; } } // handle get by unique if (input.by.unique) { // resolve the invoice ref const invoiceFound = await (0, getInvoice_1.getInvoice)({ by: { ref: input.by.unique.invoiceRef, }, }, context); if (!invoiceFound) throw new helpful_errors_1.BadRequestError('can not resolve item.invoiceRef', { input }); // lookup the items by invoice, to filter down to a subset const { data: candidates } = await context.stripe.invoiceItems.list({ invoice: invoiceFound.id, limit: 100, }); if (candidates.length >= 90) // 90 because that's too close for comfort throw new helpful_errors_1.UnexpectedCodePathError('todo: handle pagination on invoices', { found: candidates.length, limit: 100, }); // now find the one with this exid, for the invoice const targets = candidates.filter((candidate) => candidate.metadata?.exid === input.by.unique?.exid); const [target, ...otherOptions] = targets; if (otherOptions.length) throw new helpful_errors_1.UnexpectedCodePathError('more than one item matches the .unique key', { input, matches: targets }); if (!target) return null; return await (0, exports.getInvoiceItem)({ by: { primary: { id: target.id } } }, context); // find by id, to expand the discounts } // otherwise, unexpected input throw new helpful_errors_1.UnexpectedCodePathError('invalid input', { input }); }, { name: (0, visualogic_1.getResourceNameFromFileName)(__filename), }); //# sourceMappingURL=getInvoiceItem.js.map