Skip to content

Commit

Permalink
feat(handler): let consumer handle errors thrown by prisma
Browse files Browse the repository at this point in the history
  • Loading branch information
Bryant Brock committed Apr 21, 2023
1 parent 78d548b commit bf8236e
Showing 1 changed file with 17 additions and 38 deletions.
55 changes: 17 additions & 38 deletions src/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ type HandlePrismaQueryParams<
> = {
model: T;
action: A;
query?: PrismaClient[T][A] extends (...args: any) => any
? Parameters<PrismaClient[T][A]>[0]
: never;
query?: Parameters<PrismaClient[T][A]>[0] & { where?: any };
db: PrismaClient;
count?: boolean;
debug?: boolean;
Expand All @@ -29,10 +27,6 @@ type HandlePrismaQueryResult<T> = T extends undefined

type Unpromise<T> = T extends Promise<infer U> ? U : T;

const messages = {
P2002: "Name must be unique.",
};

export const handlePrismaQuery = async <
T extends ModelName,
A extends keyof PrismaClient[T]
Expand All @@ -47,36 +41,21 @@ export const handlePrismaQuery = async <
>
>
> => {
try {
const { model, action, query, db, count } = params;
const queryFn = query
? // @ts-ignore
() => db[model][action](query)
: // @ts-ignore
() => db[model][action]();

if (count) {
const [_count, data] = await db.$transaction([
// @ts-ignore
db[model].count(query?.where ? { where: query.where } : undefined),
queryFn(),
]);

return { _count, data } as HandlePrismaQueryResult<any>;
} else {
const data = await queryFn();

return data;
}
} catch (error) {
if (params.debug) {
console.error(error);
}

// @ts-ignore
const message = messages[error?.code] ?? "Something went wrong.";

// @ts-ignore
return { error: message };
const { model, action, query, db, count } = params;
const queryFn = query
? () => db[model][action](query)
: () => db[model][action]();

if (count) {
const [_count, data] = await db.$transaction([
db[model].count(query?.where ? { where: query.where } : undefined),
queryFn(),
]);

return { _count, data } as HandlePrismaQueryResult<any>;
} else {
const data = await queryFn();

return data;
}
};

0 comments on commit bf8236e

Please sign in to comment.