从零搭建基于 AI GitHub 分析平台 (7) Create Project API

设置 Authenticated Route

修改 src/server/api/trpc.ts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const isAuthenticated = t.middleware(async ({ next, ctx }) => {
const user = await auth();
if(!user){
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You must be logged in to perform this action",
});
};

return next({
ctx : {
...ctx,
user
}
});
});

export const authenticatedProcedure = publicProcedure.use(isAuthenticated);

设置 Project API

添加 src/server/api/routers/project.ts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { z } from "zod";

import { authenticatedProcedure, createTRPCRouter } from "@/server/api/trpc";

export const projectRouter = createTRPCRouter({
createProject: authenticatedProcedure.input(
z.object({
name: z.string(),
githubURL: z.string(),
githubToken: z.string().optional(),
})
).mutation(async ({ ctx , input })=>{
const project = await ctx.db.project.create({
data: {
githubURL : input.githubURL,
name: input.name,
usersProject: {
create: {
userId: ctx.user.userId ?? "",
}
}
}
});
return true;
})
});

配置 Route

修改src/server/api/root.ts:

1
2
3
4
import { projectRouter } from "@/server/api/routers/project";
export const appRouter = createTRPCRouter({
project: projectRouter,
});

页面调用

修改 src/app/(protected)/create-project/page.tsx:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { api } from "@/trpc/react";
const createProject= api.project.createProject.useMutation();

function onSubmit(data: FormInput) {
createProject.mutate({
name: data.projectName,
githubURL: data.repoURL,
githubToken: data.githubToken
}, {
onSuccess: ()=>{
toast.success("项目创建成功");
reset();
},
onError: (error)=>{
toast.error("项目创建失败");
}
});
return true;
}

测试

提交后,数据库有两条记录:


作者:Bearalise
出处:从零搭建基于 AI GitHub 分析平台 (7) Create Project API
版权:本文版权归作者所有
转载:欢迎转载,但未经作者同意,必须保留此段声明,必须在文章中给出原文链接。

请我喝杯咖啡吧~

支付宝
微信