88 lines
2.5 KiB
TypeScript
88 lines
2.5 KiB
TypeScript
/**
|
|
* GET /api/v1/libs — list all repositories
|
|
* POST /api/v1/libs — add a new repository
|
|
*/
|
|
import { json } from '@sveltejs/kit';
|
|
import type { RequestHandler } from './$types';
|
|
import { getClient } from '$lib/server/db/client';
|
|
import { RepositoryMapper } from '$lib/server/mappers/repository.mapper.js';
|
|
import { IndexingJobMapper } from '$lib/server/mappers/indexing-job.mapper.js';
|
|
import { RepositoryService } from '$lib/server/services/repository.service';
|
|
import { getQueue } from '$lib/server/pipeline/startup';
|
|
import { handleServiceError } from '$lib/server/utils/validation';
|
|
|
|
function getService() {
|
|
return new RepositoryService(getClient());
|
|
}
|
|
|
|
export const GET: RequestHandler = ({ url }) => {
|
|
try {
|
|
const service = getService();
|
|
const state = url.searchParams.get('state') as
|
|
| 'pending'
|
|
| 'indexing'
|
|
| 'indexed'
|
|
| 'error'
|
|
| undefined;
|
|
const limit = Math.min(parseInt(url.searchParams.get('limit') ?? '50'), 200);
|
|
const offset = parseInt(url.searchParams.get('offset') ?? '0');
|
|
|
|
const libraries = service.list({ state: state ?? undefined, limit, offset });
|
|
const total = service.count(state ?? undefined);
|
|
|
|
const enriched = libraries.map((repo) => ({
|
|
...RepositoryMapper.toDto(repo),
|
|
versions: service.getVersions(repo.id)
|
|
}));
|
|
|
|
return json({ libraries: enriched, total, limit, offset });
|
|
} catch (err) {
|
|
return handleServiceError(err);
|
|
}
|
|
};
|
|
|
|
export const POST: RequestHandler = async ({ request }) => {
|
|
try {
|
|
const body = await request.json();
|
|
const service = getService();
|
|
|
|
const repo = service.add({
|
|
source: body.source,
|
|
sourceUrl: body.sourceUrl,
|
|
title: body.title,
|
|
description: body.description,
|
|
branch: body.branch,
|
|
githubToken: body.githubToken
|
|
});
|
|
|
|
let jobResponse: ReturnType<typeof IndexingJobMapper.toDto> | null = null;
|
|
if (body.autoIndex !== false) {
|
|
const queue = getQueue();
|
|
const job = queue ? queue.enqueue(repo.id) : service.createIndexingJob(repo.id);
|
|
jobResponse = IndexingJobMapper.toDto(job);
|
|
}
|
|
|
|
return json(
|
|
{ library: RepositoryMapper.toDto(repo), ...(jobResponse ? { job: jobResponse } : {}) },
|
|
{ status: 201 }
|
|
);
|
|
} catch (err) {
|
|
return handleServiceError(err);
|
|
}
|
|
};
|
|
|
|
export const OPTIONS: RequestHandler = () => {
|
|
return new Response(null, {
|
|
status: 204,
|
|
headers: corsHeaders()
|
|
});
|
|
};
|
|
|
|
function corsHeaders(): Record<string, string> {
|
|
return {
|
|
'Access-Control-Allow-Origin': '*',
|
|
'Access-Control-Allow-Methods': 'GET, POST, PATCH, DELETE, OPTIONS',
|
|
'Access-Control-Allow-Headers': 'Content-Type, Authorization'
|
|
};
|
|
}
|