UNPKG

declastruct-stripe-sdk

Version:

declarative control of stripe constructs, via declastruct

43 lines 2.39 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.setInvoiceItems = void 0; const bottleneck_1 = __importDefault(require("bottleneck")); const domain_objects_1 = require("domain-objects"); const type_fns_1 = require("type-fns"); const delInvoiceItem_1 = require("./delInvoiceItem"); const getInvoiceItems_1 = require("./getInvoiceItems"); const setInvoiceItem_1 = require("./setInvoiceItem"); const oneByOne = new bottleneck_1.default({ maxConcurrent: 1 }); /** * .what = sets the items on the invoice to exactly equal the given items * .what.intent * - insert items which dont exist * - update items which changed * - delete items which were removed */ const setInvoiceItems = async (input, context) => { // sanity check that all the items are for the same invoice // todo // get the current items const itemsFound = await (0, getInvoiceItems_1.getInvoiceItems)({ by: { invoice: { by: { ref: input.to.invoiceRef } } }, }, context); // determine which items need to be deleted const getComparableUniqueIdentifier = (item) => (0, domain_objects_1.serialize)((0, type_fns_1.pick)(item, [ 'exid', // 'invoiceRef'; // note: we omit the invoice ref, since it could be in either unique or primary form and would cause false positives; however, we already know that the invoice refs are all the same in this case, so we can skip it ])); const itemsDesiredUniqueIdentifiers = input.items.map(getComparableUniqueIdentifier); const itemsToDelete = itemsFound.filter((itemFound) => !itemsDesiredUniqueIdentifiers.includes(getComparableUniqueIdentifier(itemFound))); // delete the items that should no longer be on there await Promise.all(itemsToDelete.map(async (itemToDelete) => await (0, delInvoiceItem_1.delInvoiceItem)({ by: { ref: itemToDelete } }, context))); // now set all of the desired ones await Promise.all(input.items.map((item) => // run one by one to guarantee sort order // todo: is there a declarative way to do this? oneByOne.schedule(async () => (0, setInvoiceItem_1.setInvoiceItem)({ upsert: item }, context)))); }; exports.setInvoiceItems = setInvoiceItems; //# sourceMappingURL=setInvoiceItems.js.map