Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix company router errors when fetching companies that don't exist #35

Merged
merged 1 commit into from
Feb 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,
},
});
}),
});
Loading