91 lines
2.5 KiB
TypeScript
91 lines
2.5 KiB
TypeScript
import { z } from "zod";
|
|
import { router, publicProcedure } from "../trpc";
|
|
|
|
export const companiesRouter = router({
|
|
getAll: publicProcedure.query(async ({ ctx }) => {
|
|
return await ctx.queryBuilder
|
|
.selectFrom("companies")
|
|
.select(["id", "name", "website", "notes", "createdAt", "updatedAt"])
|
|
.orderBy("createdAt", "desc")
|
|
.execute();
|
|
}),
|
|
|
|
search: publicProcedure
|
|
.input(z.object({ query: z.string(), limit: z.number().default(5) }))
|
|
.query(async ({ ctx, input }) => {
|
|
const searchTerm = input.query.trim();
|
|
|
|
// If no search term, return recent companies
|
|
if (!searchTerm) {
|
|
return await ctx.queryBuilder
|
|
.selectFrom("companies")
|
|
.select(["id", "name", "website"])
|
|
.orderBy("createdAt", "desc")
|
|
.limit(input.limit)
|
|
.execute();
|
|
}
|
|
|
|
// Search by name or website using orWhere
|
|
return await ctx.queryBuilder
|
|
.selectFrom("companies")
|
|
.select(["id", "name", "website"])
|
|
.where("name", "contains", searchTerm)
|
|
.orWhere("website", "contains", searchTerm)
|
|
.orderBy("createdAt", "desc")
|
|
.limit(input.limit)
|
|
.execute();
|
|
}),
|
|
|
|
getById: publicProcedure
|
|
.input(z.object({ id: z.number() }))
|
|
.query(async ({ ctx, input }) => {
|
|
return await ctx.queryBuilder
|
|
.selectFrom("companies")
|
|
.select(["id", "name", "website", "notes", "createdAt", "updatedAt"])
|
|
.where("id", "=", input.id)
|
|
.executeTakeFirst();
|
|
}),
|
|
|
|
create: publicProcedure
|
|
.input(
|
|
z.object({
|
|
name: z.string().min(1),
|
|
website: z.string().optional(),
|
|
notes: z.string().optional(),
|
|
})
|
|
)
|
|
.mutation(async ({ ctx, input }) => {
|
|
return await ctx.queryBuilder
|
|
.insertInto("companies")
|
|
.values(input)
|
|
.executeTakeFirst();
|
|
}),
|
|
|
|
update: publicProcedure
|
|
.input(
|
|
z.object({
|
|
id: z.number(),
|
|
name: z.string().optional(),
|
|
website: z.string().optional(),
|
|
notes: z.string().optional(),
|
|
})
|
|
)
|
|
.mutation(async ({ ctx, input }) => {
|
|
const { id, ...data } = input;
|
|
return await ctx.queryBuilder
|
|
.update("companies")
|
|
.set(data)
|
|
.where("id", "=", id)
|
|
.execute();
|
|
}),
|
|
|
|
delete: publicProcedure
|
|
.input(z.object({ id: z.number() }))
|
|
.mutation(async ({ ctx, input }) => {
|
|
return await ctx.queryBuilder
|
|
.deleteFrom("companies")
|
|
.where("id", "=", input.id)
|
|
.execute();
|
|
}),
|
|
});
|