respository.ts90 lines, 2.5 KB
| 1 | import { z } from "zod"; |
| 2 | import { TRPCError } from "@trpc/server"; |
| 3 | import { createTRPCRouter, protectedProcedure } from "../trpc"; |
| 4 | import { |
| 5 | fetchGitHubRepos, |
| 6 | getGitHubAccessToken, |
| 7 | } from "@/server/services/github"; |
| 8 | |
| 9 | export const repositoryRouter = createTRPCRouter({ |
| 10 | list: protectedProcedure.query(async ({ ctx }) => { |
| 11 | const repositories = await ctx.db.repository.findMany({ |
| 12 | where: { userId: ctx.user.id }, |
| 13 | orderBy: { createdAt: "desc" }, |
| 14 | }); |
| 15 | return repositories; |
| 16 | }), |
| 17 | |
| 18 | fetchFromGithub: protectedProcedure.query(async ({ ctx }) => { |
| 19 | const accessToken = await getGitHubAccessToken(ctx.user.id); |
| 20 | |
| 21 | if (!accessToken) { |
| 22 | throw new TRPCError({ |
| 23 | code: "PRECONDITION_FAILED", |
| 24 | message: "User has not authorized GitHub access", |
| 25 | }); |
| 26 | } |
| 27 | |
| 28 | const repos = await fetchGitHubRepos(accessToken); |
| 29 | return repos.map((repo) => ({ |
| 30 | githubId: repo.id, |
| 31 | name: repo.name, |
| 32 | fullName: repo.full_name, |
| 33 | private: repo.private, |
| 34 | htmlUrl: repo.html_url, |
| 35 | description: repo.description, |
| 36 | language: repo.language, |
| 37 | stars: repo.stargazers_count, |
| 38 | updatedAt: repo.updated_at, |
| 39 | })); |
| 40 | }), |
| 41 | |
| 42 | connect: protectedProcedure |
| 43 | .input( |
| 44 | z.object({ |
| 45 | repos: z.array( |
| 46 | z.object({ |
| 47 | githubId: z.number(), |
| 48 | name: z.string(), |
| 49 | fullName: z.string(), |
| 50 | private: z.boolean(), |
| 51 | htmlUrl: z.string(), |
| 52 | }), |
| 53 | ), |
| 54 | }), |
| 55 | ) |
| 56 | .mutation(async ({ ctx, input }) => { |
| 57 | const result = await Promise.all( |
| 58 | input.repos.map((repo) => |
| 59 | ctx.db.repository.upsert({ |
| 60 | where: { githubId: repo.githubId }, |
| 61 | create: { |
| 62 | userId: ctx.user.id, |
| 63 | githubId: repo.githubId, |
| 64 | name: repo.name, |
| 65 | fullName: repo.fullName, |
| 66 | private: repo.private, |
| 67 | htmlUrl: repo.htmlUrl, |
| 68 | }, |
| 69 | update: { |
| 70 | name: repo.name, |
| 71 | fullName: repo.fullName, |
| 72 | private: repo.private, |
| 73 | htmlUrl: repo.htmlUrl, |
| 74 | updatedAt: new Date(), |
| 75 | }, |
| 76 | }), |
| 77 | ), |
| 78 | ); |
| 79 | return { connected: result.length }; |
| 80 | }), |
| 81 | |
| 82 | disconnect: protectedProcedure |
| 83 | .input(z.object({ id: z.string() })) |
| 84 | .mutation(async ({ ctx, input }) => { |
| 85 | await ctx.db.repository.delete({ |
| 86 | where: { id: input.id, userId: ctx.user.id }, |
| 87 | }); |
| 88 | return { success: true }; |
| 89 | }), |
| 90 | }); |