service

 avatar
unknown
typescript
9 months ago
1.5 kB
16
Indexable
export const createUserAndProfile = async (profileName: string, email: string, dateOfBirth: Date, hashedPassword: string, username: string, profilePicture: string) => {
    try {
        return await prisma.$transaction(async (prisma) => {
            // Create user first
            const user = await prisma.user.create({
                data: {
                    username: username,
                    email: email,
                    dateOfBirth: dateOfBirth,
                    password: hashedPassword,
                },
            });

            // Create profile for that user
            const profile = await prisma.profile.create({
                data: {
                    name: profileName,
                    bio: '',
                    location: '',
                    websiteUrl: '',
                    profilePicture: profilePicture,
                    bannerPicture: '',
                    userId: user.id,
                },
            });

            return { user };
        });
    } catch (error) {
        if (error instanceof Prisma.PrismaClientKnownRequestError) {
            if (error.code === 'P2002') {
                // Unique constraint violation (e.g. username or email already exists)
                return { error: 'Unique constraint violation', fields: (error.meta?.target as string[]) ?? [] };
            }
        }

        return { error: getErrorMessage(error), fields: [] };
    }
};
Editor is loading...
Leave a Comment