| gio | 7f98e77 | 2025-05-07 11:00:14 +0000 | [diff] [blame] | 1 | import axios from 'axios'; |
| 2 | import { z } from 'zod'; |
| 3 | |
| 4 | export const GithubRepositorySchema = z.object({ |
| 5 | id: z.number(), |
| 6 | name: z.string(), |
| 7 | full_name: z.string(), |
| 8 | html_url: z.string(), |
| 9 | ssh_url: z.string(), |
| 10 | }); |
| 11 | |
| 12 | export type GithubRepository = z.infer<typeof GithubRepositorySchema>; |
| 13 | |
| 14 | export class GithubClient { |
| 15 | private token: string; |
| 16 | |
| 17 | constructor(token: string) { |
| 18 | this.token = token; |
| 19 | } |
| 20 | |
| 21 | private getHeaders() { |
| 22 | return { |
| 23 | "Authorization": `Bearer ${this.token}`, |
| 24 | "Accept": "application/vnd.github.v3+json", |
| 25 | }; |
| 26 | } |
| 27 | |
| 28 | async getRepositories(): Promise<GithubRepository[]> { |
| 29 | const response = await axios.get("https://api.github.com/user/repos", { |
| 30 | headers: this.getHeaders(), |
| 31 | }); |
| 32 | return z.array(GithubRepositorySchema).parse(response.data); |
| 33 | } |
| 34 | |
| 35 | async addDeployKey(repoPath: string, key: string) { |
| 36 | const sshUrl = repoPath; |
| 37 | const repoOwnerAndName = sshUrl.replace('git@github.com:', '').replace('.git', ''); |
| 38 | |
| 39 | await axios.post( |
| 40 | `https://api.github.com/repos/${repoOwnerAndName}/keys`, |
| 41 | { |
| 42 | title: "dodo", |
| 43 | key: key, |
| 44 | read_only: true |
| 45 | }, |
| 46 | { |
| 47 | headers: this.getHeaders(), |
| 48 | } |
| 49 | ); |
| 50 | } |
| 51 | } |