declastruct-stripe-sdk
Version:
declarative control of stripe constructs, via declastruct
62 lines • 3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.setCustomer = void 0;
const domain_objects_1 = require("domain-objects");
const hash_fns_1 = require("hash-fns");
const helpful_errors_1 = require("helpful-errors");
const visualogic_1 = require("visualogic");
const castToDeclaredStripeCustomer_1 = require("../cast/castToDeclaredStripeCustomer");
const getCustomer_1 = require("./getCustomer");
exports.setCustomer = (0, visualogic_1.withLogTrail)(async (input, context) => {
// lookup the customer
const customerFound = await (0, getCustomer_1.getCustomer)({
by: {
unique: {
email: input.finsert?.email ??
input.upsert?.email ??
helpful_errors_1.UnexpectedCodePathError.throw('no email in input', { input }),
},
},
}, context);
// sanity check that if the customer exists, their id matches the user's expectations, if any
const stripeCustomerIdExpected = input.finsert?.id || input.upsert?.id;
if (customerFound &&
stripeCustomerIdExpected &&
stripeCustomerIdExpected !== customerFound.id)
throw new helpful_errors_1.UnexpectedCodePathError('asked to setCustomer with a .primary=id which does not match the .unique=email', {
stripeCustomerIdExpected,
stripeCustomerIdFound: customerFound.id,
customerFound,
});
// if the customer was found, then handle that
if (customerFound) {
// if asked to finsert, then we can return it now
if (input.finsert)
return customerFound;
// if asked to upsert, then we can update it now
if (input.upsert)
return (0, castToDeclaredStripeCustomer_1.castToDeclaredStripeCustomer)(await context.stripe.customers.update(customerFound.id, {
name: input.upsert.name ?? undefined,
description: input.upsert.description ?? undefined,
phone: input.upsert.phone ?? undefined,
metadata: input.upsert.metadata ?? undefined,
}));
}
// otherwise, create the customer
const customerDesired = input.upsert ?? input.finsert;
const customerCreated = await context.stripe.customers.create({
email: customerDesired.email,
name: customerDesired.name ?? undefined,
description: customerDesired.description ?? undefined,
phone: customerDesired.phone ?? undefined,
metadata: customerDesired.metadata ?? undefined,
}, {
idempotencyKey: (0, hash_fns_1.toHashSha256Sync)([
// stage, // todo: pull stage from context.environment
'v1.0.0',
(0, domain_objects_1.serialize)({ ...customerDesired }),
].join(';')),
});
return (0, castToDeclaredStripeCustomer_1.castToDeclaredStripeCustomer)(customerCreated);
}, { name: (0, visualogic_1.getResourceNameFromFileName)(__filename) });
//# sourceMappingURL=setCustomer.js.map