more files

This commit is contained in:
2026-05-06 23:19:35 +02:00
parent 563f82d497
commit 1634c4cc0d
22 changed files with 2959 additions and 119 deletions
+72
View File
@@ -0,0 +1,72 @@
import { z } from 'zod'
let csrfToken: string | null = null
async function getCSRFToken(): Promise<string> {
if (csrfToken) return csrfToken
const res = await fetch('/api/v1/csrf', { credentials: 'include' })
if (!res.ok) throw new Error('Failed to fetch CSRF token')
csrfToken = res.headers.get('X-CSRF-Token') ?? ''
return csrfToken
}
export class ApiError extends Error {
constructor(
public readonly status: number,
message: string,
) {
super(message)
this.name = 'ApiError'
}
}
interface RequestOptions extends RequestInit {
json?: unknown
}
async function request<T>(
path: string,
schema: z.ZodType<T>,
options: RequestOptions = {},
): Promise<T> {
const { json, ...rest } = options
const headers: Record<string, string> = {}
if (json !== undefined) {
headers['Content-Type'] = 'application/json'
}
const method = (rest.method ?? 'GET').toUpperCase()
if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
headers['X-CSRF-Token'] = await getCSRFToken()
}
const res = await fetch(path, {
...rest,
credentials: 'include',
headers: { ...headers, ...(rest.headers as Record<string, string> | undefined) },
body: json !== undefined ? JSON.stringify(json) : rest.body,
})
if (!res.ok) {
let message = res.statusText
try {
const body = await res.json()
if (typeof body.error === 'string') message = body.error
} catch {}
throw new ApiError(res.status, message)
}
const data = await res.json()
return schema.parse(data)
}
export const api = {
get: <T>(path: string, schema: z.ZodType<T>) => request(path, schema),
post: <T>(path: string, schema: z.ZodType<T>, body: unknown) =>
request(path, schema, { method: 'POST', json: body }),
put: <T>(path: string, schema: z.ZodType<T>, body: unknown) =>
request(path, schema, { method: 'PUT', json: body }),
delete: <T>(path: string, schema: z.ZodType<T>) =>
request(path, schema, { method: 'DELETE' }),
}
+37
View File
@@ -0,0 +1,37 @@
import { useQuery } from '@tanstack/react-query'
import { z } from 'zod'
import { api } from '../client'
import type { Pipeline } from '../../types/api'
const pipelineSchema = z.object({
id: z.number(),
repoId: z.number(),
ref: z.string(),
status: z.enum(['pending', 'running', 'success', 'failure', 'cancelled']),
createdAt: z.string(),
updatedAt: z.string(),
})
const pipelinesSchema = z.array(pipelineSchema)
export function usePipelines(owner: string, repo: string) {
return useQuery({
queryKey: ['repos', owner, repo, 'pipelines'],
queryFn: () =>
api.get<Pipeline[]>(`/api/v1/repos/${owner}/${repo}/pipelines`, pipelinesSchema),
enabled: Boolean(owner && repo),
refetchInterval: 5000, // poll while pipelines may be running
})
}
export function usePipeline(owner: string, repo: string, runId: number) {
return useQuery({
queryKey: ['repos', owner, repo, 'pipelines', runId],
queryFn: () =>
api.get<Pipeline>(
`/api/v1/repos/${owner}/${repo}/pipelines/${runId}`,
pipelineSchema,
),
enabled: Boolean(owner && repo && runId),
})
}
+50
View File
@@ -0,0 +1,50 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { z } from 'zod'
import { api } from '../client'
import type { PullRequest } from '../../types/api'
const prSchema = z.object({
id: z.number(),
repoId: z.number(),
authorId: z.number(),
title: z.string(),
body: z.string(),
sourceBranch: z.string(),
targetBranch: z.string(),
status: z.enum(['open', 'merged', 'closed']),
createdAt: z.string(),
updatedAt: z.string(),
})
const prsSchema = z.array(prSchema)
const mergeResponseSchema = z.object({ status: z.string() })
export function usePRs(owner: string, repo: string) {
return useQuery({
queryKey: ['repos', owner, repo, 'pulls'],
queryFn: () =>
api.get<PullRequest[]>(`/api/v1/repos/${owner}/${repo}/pulls`, prsSchema),
enabled: Boolean(owner && repo),
})
}
export function usePR(owner: string, repo: string, prId: number) {
return useQuery({
queryKey: ['repos', owner, repo, 'pulls', prId],
queryFn: () =>
api.get<PullRequest>(`/api/v1/repos/${owner}/${repo}/pulls/${prId}`, prSchema),
enabled: Boolean(owner && repo && prId),
})
}
export function useMergePR(owner: string, repo: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (prId: number) =>
api.post(`/api/v1/repos/${owner}/${repo}/pulls/${prId}/merge`, mergeResponseSchema, {}),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['repos', owner, repo, 'pulls'] })
},
})
}
+65
View File
@@ -0,0 +1,65 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { z } from 'zod'
import { api } from '../client'
import type { Repository, TreeEntry } from '../../types/api'
const repositorySchema = z.object({
id: z.number(),
ownerId: z.number(),
name: z.string(),
description: z.string(),
isPrivate: z.boolean(),
defaultBranch: z.string(),
createdAt: z.string(),
updatedAt: z.string(),
})
const repositoriesSchema = z.array(repositorySchema)
const treeEntrySchema = z.object({
mode: z.string(),
type: z.enum(['blob', 'tree']),
hash: z.string(),
name: z.string(),
})
const treeSchema = z.array(treeEntrySchema)
export function useRepos() {
return useQuery({
queryKey: ['repos'],
queryFn: () => api.get<Repository[]>('/api/v1/repos', repositoriesSchema),
})
}
export function useRepo(owner: string, name: string) {
return useQuery({
queryKey: ['repos', owner, name],
queryFn: () =>
api.get<Repository>(`/api/v1/repos/${owner}/${name}`, repositorySchema),
enabled: Boolean(owner && name),
})
}
export function useRepoTree(owner: string, name: string, ref: string, path = '') {
return useQuery({
queryKey: ['repos', owner, name, 'tree', ref, path],
queryFn: () =>
api.get<TreeEntry[]>(
`/api/v1/repos/${owner}/${name}/tree?ref=${ref}&path=${path}`,
treeSchema,
),
enabled: Boolean(owner && name && ref),
})
}
export function useCreateRepo() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (data: { name: string; description?: string; isPrivate?: boolean }) =>
api.post<Repository>('/api/v1/repos', repositorySchema, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['repos'] })
},
})
}