Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions src/app/api/v2/repositories/[...fullName]/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/**
* Copyright 2026 Lifecycle contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { NextRequest } from 'next/server';

const mockRemoveRepository = jest.fn();

jest.mock('server/services/repository', () => ({
__esModule: true,
default: jest.fn().mockImplementation(() => ({
removeRepository: mockRemoveRepository,
})),
}));

import { DELETE } from './route';

function makeRequest(url = 'http://localhost/api/v2/repositories/example-org/api') {
return {
headers: new Headers([['x-request-id', 'req-test']]),
nextUrl: new URL(url),
} as unknown as NextRequest;
}

describe('DELETE /api/v2/repositories/{owner}/{repo}', () => {
beforeEach(() => {
jest.clearAllMocks();
mockRemoveRepository.mockResolvedValue({
id: 1,
fullName: 'example-org/api',
onboarded: false,
deletedAt: '2026-01-01T00:00:00.000Z',
});
});

test('soft-removes the repository by owner/repo path', async () => {
const response = await DELETE(makeRequest(), {
params: {
fullName: ['example-org', 'api'],
},
});
const body = await response.json();

expect(response.status).toBe(200);
expect(mockRemoveRepository).toHaveBeenCalledWith('example-org/api', undefined);
expect(body.data.repository).toEqual({
id: 1,
fullName: 'example-org/api',
onboarded: false,
deletedAt: '2026-01-01T00:00:00.000Z',
});
});

test('passes installationId through when provided', async () => {
const response = await DELETE(
makeRequest('http://localhost/api/v2/repositories/example-org/api?installationId=34'),
{
params: {
fullName: ['example-org', 'api'],
},
}
);

expect(response.status).toBe(200);
expect(mockRemoveRepository).toHaveBeenCalledWith('example-org/api', 34);
});

test('rejects incomplete repository paths', async () => {
const response = await DELETE(makeRequest(), {
params: {
fullName: ['example-org'],
},
});
const body = await response.json();

expect(response.status).toBe(400);
expect(body.error.message).toContain('Invalid repository fullName');
});
});
99 changes: 99 additions & 0 deletions src/app/api/v2/repositories/[...fullName]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/**
* Copyright 2026 Lifecycle contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { NextRequest } from 'next/server';
import { createApiHandler } from 'server/lib/createApiHandler';
import { errorResponse, successResponse } from 'server/lib/response';
import RepositoryService from 'server/services/repository';

interface RouteContext {
params: {
fullName?: string[];
};
}

/**
* @openapi
* /api/v2/repositories/{owner}/{repo}:
* delete:
* summary: Remove an onboarded repository
* description: Soft-removes a repository from Lifecycle onboarding while preserving historical data.
* tags:
* - Repositories
* operationId: removeRepository
* parameters:
* - in: path
* name: owner
* required: true
* schema:
* type: string
* - in: path
* name: repo
* required: true
* schema:
* type: string
* - in: query
* name: installationId
* schema:
* type: integer
* responses:
* '200':
* description: Repository removed.
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/RemoveRepositorySuccessResponse'
* '400':
* description: Invalid repository full name.
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ApiErrorResponse'
* '404':
* description: Repository not found.
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ApiErrorResponse'
*/
const deleteHandler = async (req: NextRequest, { params }: RouteContext) => {
const segments = params.fullName || [];
if (segments.length < 2) {
return errorResponse(new Error('Invalid repository fullName. Expected format: owner/repo'), { status: 400 }, req);
}

const rawInstallationId = req.nextUrl.searchParams.get('installationId');
const installationId = rawInstallationId ? Number(rawInstallationId) : undefined;
if (rawInstallationId && !Number.isFinite(installationId)) {
return errorResponse(new Error('installationId must be a number'), { status: 400 }, req);
}

try {
const repository = await new RepositoryService().removeRepository(segments.join('/'), installationId);
return successResponse({ repository }, { status: 200 }, req);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (message.includes('Invalid repository fullName')) {
return errorResponse(error, { status: 400 }, req);
}
if (message.includes('Repository not found')) {
return errorResponse(error, { status: 404 }, req);
}
throw error;
}
};

export const DELETE = createApiHandler(deleteHandler);
132 changes: 132 additions & 0 deletions src/app/api/v2/repositories/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/**
* Copyright 2026 Lifecycle contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { NextRequest } from 'next/server';

const mockListOnboardedRepositories = jest.fn();
const mockListInstalledRepositories = jest.fn();
const mockOnboardRepository = jest.fn();
const mockParseOnboardedParam = jest.fn((value?: string | null) => {
if (value === 'true') return true;
if (value === 'false') return false;
return undefined;
});

jest.mock('server/services/repository', () => ({
__esModule: true,
default: jest.fn().mockImplementation(() => ({
listOnboardedRepositories: mockListOnboardedRepositories,
listInstalledRepositories: mockListInstalledRepositories,
onboardRepository: mockOnboardRepository,
parseOnboardedParam: mockParseOnboardedParam,
})),
}));

import { GET, POST } from './route';

function makeRequest(url: string, body?: unknown) {
return {
headers: new Headers([['x-request-id', 'req-test']]),
nextUrl: new URL(url),
json: jest.fn().mockResolvedValue(body || {}),
} as unknown as NextRequest;
}

describe('/api/v2/repositories', () => {
beforeEach(() => {
jest.clearAllMocks();
mockListOnboardedRepositories.mockResolvedValue({
repositories: [{ id: 1, fullName: 'example-org/api', onboarded: true }],
pagination: { current: 1, total: 1, items: 1, limit: 25 },
});
mockListInstalledRepositories.mockResolvedValue({
repositories: [{ githubRepositoryId: 2, fullName: 'example-org/web', onboarded: false }],
pagination: { current: 1, total: 1, items: 1, limit: 25 },
});
mockOnboardRepository.mockResolvedValue({
repository: { id: 1, fullName: 'example-org/api', onboarded: true },
created: true,
});
});

describe('GET', () => {
test('lists onboarded repositories by default', async () => {
const response = await GET(makeRequest('http://localhost/api/v2/repositories?q=api&page=2&limit=10'));
const body = await response.json();

expect(response.status).toBe(200);
expect(mockListOnboardedRepositories).toHaveBeenCalledWith({
query: 'api',
page: 2,
limit: 10,
installationId: undefined,
});
expect(body.data.repositories).toEqual([{ id: 1, fullName: 'example-org/api', onboarded: true }]);
expect(body.metadata.pagination).toEqual({ current: 1, total: 1, items: 1, limit: 25 });
});

test('lists installed repositories annotated for dropdown filtering', async () => {
const response = await GET(
makeRequest('http://localhost/api/v2/repositories?view=all&onboarded=false&q=web&refresh=true')
);

expect(response.status).toBe(200);
expect(mockParseOnboardedParam).toHaveBeenCalledWith('false');
expect(mockListInstalledRepositories).toHaveBeenCalledWith({
query: 'web',
page: 1,
limit: 25,
installationId: undefined,
onboarded: false,
refresh: true,
});
});

test('rejects unknown views', async () => {
const response = await GET(makeRequest('http://localhost/api/v2/repositories?view=legacy'));
const body = await response.json();

expect(response.status).toBe(400);
expect(body.error.message).toContain('view must be onboarded or all');
});
});

describe('POST', () => {
test('onboards a repository and returns 201 for newly created rows', async () => {
const response = await POST(
makeRequest('http://localhost/api/v2/repositories', {
fullName: 'example-org/api',
})
);
const body = await response.json();

expect(response.status).toBe(201);
expect(mockOnboardRepository).toHaveBeenCalledWith('example-org/api', undefined);
expect(body.data).toEqual({
repository: { id: 1, fullName: 'example-org/api', onboarded: true },
created: true,
});
});

test('rejects missing fullName', async () => {
const response = await POST(makeRequest('http://localhost/api/v2/repositories', {}));
const body = await response.json();

expect(response.status).toBe(400);
expect(body.error.message).toContain('Missing required field: fullName');
});
});
});
Loading
Loading