import type {LogContext} from '@rocicorp/logger'; import {v4 as uuidv4} from 'uuid'; import type { CreateCustomerRequest, CreateCustomerResponse, } from './api-types.js'; import {ValidationError} from './handler-errors.js'; import {prisma} from './db.js'; export async function createCustomer( req: CreateCustomerRequest, lc: LogContext, ): Promise { lc = lc.withContext('createCustomer'); lc.debug?.('request', req); if (!/\S+/.test(req.name)) { throw new ValidationError('name is required'); } else if (!/^[^@]+@[^@]+\.[^@]+$/.test(req.email)) { throw new ValidationError('email is invalid'); } else if (!req.acceptedTOS) { throw new ValidationError('acceptedTOS is required'); } // License keys start with "l" and have no dashes. const licenseKey = 'l' + uuidv4().replace(/-/g, ''); const customer = await prisma.customer.create({ data: { // TODO we should probably validate the name against a regexp? name: req.name, // TODO(arv): Unclear why this is | null and not | undefined. Maybe a prisma bug? project: req.project ?? null, email: req.email, license: { create: { key: licenseKey, commercial: req.commercial, acceptedTOS: req.acceptedTOS, }, }, }, }); lc.info?.('Created customer ', customer); return {licenseKey}; }