vevcom / projectNext

Project Next is Omegas new website coming soon
MIT License
7 stars 0 forks source link

refactor/Better-errorSoulution-and-prisma-logging #207

Open JohanHjelsethStorstad opened 6 months ago

JohanHjelsethStorstad commented 6 months ago

This is a suggestion. I really do not like try catch patterns. And we need a standard way to do logging. This Is a suggestion where we combine the two into one prisma call wrapper:

export async function prismaCall<T>(
    prismaFn: () => Promise<T>,
    callType: 'UPDATE' | 'CREATE' | 'DESTROY' | 'READ',
    model: Prisma.ModelName,
    message?: string
): Promise<ActionReturn<T>> {
    try {
        const ret = await prismaFn()
        logger.info(`${callType} - success for ${model} ${message ? `: ${message}` : ''}`)
        return { success: true, data: ret }
    } catch (error) {
        logger.error(`${callType} - failed for ${model} ${message ? `: ${message}` : ''}`)
        return createPrismaActionError(error)
    }
}

Used like this:

export async function createUser(data: CreateUserType): Promise<ActionReturn<User>> {
    const passwordHash = data.password //TODO: hash password
    return await prismaCall(() => prisma.user.create({
        data: {
            ...data,
            credentials: {
                create: {
                    passwordHash
                },
            },
        },
    }), 'CREATE', 'User')
}