Skip to content

Commit

Permalink
fix: fix company router errors when fetching companies that don't exi…
Browse files Browse the repository at this point in the history
…st (#35)
  • Loading branch information
banushi-a authored Feb 11, 2024
1 parent 83e28e5 commit 0623618
Showing 1 changed file with 58 additions and 16 deletions.
74 changes: 58 additions & 16 deletions src/server/api/routers/company.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,35 @@
import { z } from "zod";
import {
createTRPCRouter,
protectedProcedure,
publicProcedure,
} from "~/server/api/trpc";
import { createCompanySchema, updateCompanySchema } from "~/schema/company";
import { getByIdSchema, getByNameSchema } from "~/schema/misc";
import { TRPCError } from "@trpc/server";

export const companyRouter = createTRPCRouter({
list: publicProcedure.query(({ ctx }) => {
return ctx.db.company.findMany();
}),
getByName: publicProcedure.input(getByNameSchema).query(({ ctx, input }) => {
return ctx.db.company.findFirst({
where: {
name: input.name,
},
});
}),
getByName: publicProcedure
.input(getByNameSchema)
.query(async ({ ctx, input }) => {
// Ensure A Company Exists Before Getting It
const existingCompany = await ctx.db.company.findFirst({
where: {
name: input.name,
},
});

if (!existingCompany) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Company not found",
});
}

return existingCompany;
}),
create: protectedProcedure
.input(createCompanySchema)
.mutation(({ ctx, input }) => {
Expand All @@ -32,7 +44,21 @@ export const companyRouter = createTRPCRouter({
}),
update: protectedProcedure
.input(updateCompanySchema)
.mutation(({ ctx, input }) => {
.mutation(async ({ ctx, input }) => {
// Ensure A Company Exists Before Updating It
const existingCompany = await ctx.db.company.findUnique({
where: {
id: input.id,
},
});

if (!existingCompany) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Company not found",
});
}

return ctx.db.company.update({
where: {
id: input.id,
Expand All @@ -42,11 +68,27 @@ export const companyRouter = createTRPCRouter({
},
});
}),
delete: protectedProcedure.input(getByIdSchema).mutation(({ ctx, input }) => {
return ctx.db.company.delete({
where: {
id: input.id,
},
});
}),
delete: protectedProcedure
.input(getByIdSchema)
.mutation(async ({ ctx, input }) => {
// Ensure A Company Exists Before Deleting It
const existingCompany = await ctx.db.company.findUnique({
where: {
id: input.id,
},
});

if (!existingCompany) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Company not found",
});
}

return ctx.db.company.delete({
where: {
id: input.id,
},
});
}),
});

0 comments on commit 0623618

Please sign in to comment.