diff --git a/src/gitea/gitea.service.ts b/src/gitea/gitea.service.ts index 94af1da..97a3d76 100644 --- a/src/gitea/gitea.service.ts +++ b/src/gitea/gitea.service.ts @@ -96,8 +96,10 @@ export class GiteaService { async listCommits(owner: string, repo: string, query: ListGiteaCommitsQuery) { const params = new URLSearchParams(); - params.set('limit', query.limit ?? '20'); - params.set('page', query.page ?? '1'); + const page = toPositiveInt(query.page, 1); + const limit = Math.min(toPositiveInt(query.limit, 20), 100); + params.set('limit', String(limit)); + params.set('page', String(page)); if (query.sha) { params.set('sha', query.sha); } @@ -108,11 +110,11 @@ export class GiteaService { params.set('until', query.until); } - const commits = await this.request( + const { data: commits, total } = await this.requestJsonWithMeta( `/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/commits?${params.toString()}`, ); - return { commits }; + return { commits, total, page, limit }; } async getCommitDiff(owner: string, repo: string, sha: string) { @@ -273,6 +275,37 @@ export class GiteaService { return (await response.json()) as T; } + private async requestJsonWithMeta( + path: string, + init?: RequestInit, + ): Promise<{ data: T; total: number | null }> { + const response = await fetch(`${this.baseUrl}${path}`, { + ...init, + headers: { + Accept: 'application/json', + ...(this.token ? { Authorization: `token ${this.token}` } : {}), + ...init?.headers, + }, + }); + + if (!response.ok) { + const message = await response.text(); + throw new BadGatewayException({ + message: 'Gitea API 요청이 실패했습니다.', + status: response.status, + detail: message, + }); + } + + const totalHeader = response.headers.get('x-total-count'); + const total = totalHeader ? Number(totalHeader) : null; + + return { + data: (await response.json()) as T, + total: Number.isFinite(total) ? total : null, + }; + } + private async requestText(path: string): Promise { const response = await fetch(`${this.baseUrl}${path}`, { headers: { @@ -348,3 +381,8 @@ function toCreateRepoPayload(body: CreateGiteaRepoDto) { auto_init: body.autoInit ?? true, }; } + +function toPositiveInt(value: string | undefined, fallback: number) { + const parsed = Number(value); + return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback; +}