( fastify: FastifyInstance, email: string )
| 9 | * @returns The existing or newly created user. |
| 10 | */ |
| 11 | export const findOrCreateUser = async ( |
| 12 | fastify: FastifyInstance, |
| 13 | email: string |
| 14 | ): Promise<{ id: string; acceptedPrivacyTerms: boolean }> => { |
| 15 | // TODO: handle the case where there are multiple users with the same email. |
| 16 | // e.g. use findMany and throw an error if more than one is found. |
| 17 | const existingUser = await fastify.prisma.user.findMany({ |
| 18 | where: { email }, |
| 19 | select: { id: true, acceptedPrivacyTerms: true } |
| 20 | }); |
| 21 | if (existingUser.length > 1) { |
| 22 | fastify.Sentry.captureException( |
| 23 | new Error( |
| 24 | `Multiple user records found for: ${existingUser.map(user => user.id).join(', ')}` |
| 25 | ) |
| 26 | ); |
| 27 | } |
| 28 | |
| 29 | if (existingUser[0]) { |
| 30 | return existingUser[0]; |
| 31 | } |
| 32 | |
| 33 | // Create new user |
| 34 | const newUser = await fastify.prisma.user.create({ |
| 35 | data: createUserInput(email), |
| 36 | select: { id: true, acceptedPrivacyTerms: true } |
| 37 | }); |
| 38 | |
| 39 | // Create drip campaign record if feature flag is enabled |
| 40 | if (fastify.gb.isOn('drip-campaign')) { |
| 41 | try { |
| 42 | const variant = assignVariantBucket(newUser.id); |
| 43 | await fastify.prisma.dripCampaign.create({ |
| 44 | data: { |
| 45 | userId: newUser.id, |
| 46 | email, |
| 47 | variant |
| 48 | } |
| 49 | }); |
| 50 | fastify.log.info( |
| 51 | `Drip campaign record created for user ${newUser.id} with variant ${variant}` |
| 52 | ); |
| 53 | } catch (error) { |
| 54 | // Log the error but don't fail user creation |
| 55 | fastify.log.error( |
| 56 | error, |
| 57 | `Failed to create drip campaign record for user ${newUser.id}` |
| 58 | ); |
| 59 | fastify.Sentry.captureException(error); |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | return newUser; |
| 64 | }; |
no test coverage detected