chat fab
This commit is contained in:
@@ -8,6 +8,7 @@ import { cvEntryRouter } from "./cvEntry";
|
||||
import { musicRouter } from "./music";
|
||||
import { trpcCrudRouterFromDrizzleEntity } from "../lib";
|
||||
import { cvCategory } from "../dbschema/schema";
|
||||
import { chatRouter } from "./chat";
|
||||
|
||||
export const trpcRouter = router({
|
||||
project: trpcCrudRouterFromDrizzleEntity('project').router,
|
||||
@@ -19,6 +20,7 @@ export const trpcRouter = router({
|
||||
entry: trpcCrudRouterFromDrizzleEntity('cvEntry').router,
|
||||
entryv2: cvEntryRouter,
|
||||
music: musicRouter,
|
||||
chat: chatRouter
|
||||
});
|
||||
|
||||
export type TrpcRouter = typeof trpcRouter;
|
||||
|
||||
53
src/server/routers/chat.ts
Normal file
53
src/server/routers/chat.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { auth } from '@clerk/nextjs/server'
|
||||
import { publicProcedure, router } from "../trpc";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { db } from '~/server/db'
|
||||
import { chatSession, systemSettings } from "../dbschema/schema";
|
||||
import { isAdmin } from '~/app/actions';
|
||||
import { z } from 'zod';
|
||||
export const chatRouter = router({
|
||||
getSession: publicProcedure.query(async () => {
|
||||
const { userId } = await auth();
|
||||
if (userId == null) {
|
||||
throw new TRPCError({message: "chat is only available to signed in users",code: 'UNAUTHORIZED'});
|
||||
}
|
||||
let session = await db.query.chatSession.findFirst({
|
||||
with: {
|
||||
messages: true
|
||||
},
|
||||
where(fields, operators) {
|
||||
return operators.eq(fields.userId,userId)
|
||||
},
|
||||
})
|
||||
if (session !== undefined) {
|
||||
return session;
|
||||
}
|
||||
let newSession = await db.insert(chatSession).values({userId: userId}).returning().execute().then((r) => r.at(0));
|
||||
if (newSession == undefined) {
|
||||
throw new TRPCError({message: "failed to create session", code:"INTERNAL_SERVER_ERROR"});
|
||||
}
|
||||
session = await db.query.chatSession.findFirst({
|
||||
with: {
|
||||
messages: true
|
||||
},
|
||||
where(fields, operators) {
|
||||
return operators.eq(fields.id,newSession.id)
|
||||
},
|
||||
})
|
||||
if (session == undefined) {
|
||||
throw new TRPCError({message: "session not found", code:"NOT_FOUND"});
|
||||
}
|
||||
if (session !== undefined) {
|
||||
return session;
|
||||
}
|
||||
}),
|
||||
getSystemPrompt: publicProcedure.query(async () => {
|
||||
const row = await db.select().from(systemSettings).limit(1).then((r) => r[0])
|
||||
return row?.systemPropmt ?? ''
|
||||
}),
|
||||
updateSystemPrompt: publicProcedure.input(z.object({ prompt: z.string() })).mutation(async ({ input }) => {
|
||||
if (!(await isAdmin())) throw new TRPCError({ code: 'FORBIDDEN' })
|
||||
await db.delete(systemSettings)
|
||||
await db.insert(systemSettings).values({ systemPropmt: input.prompt })
|
||||
}),
|
||||
})
|
||||
Reference in New Issue
Block a user