Add src/app/api/projects/route.ts
This commit is contained in:
60
src/app/api/projects/route.ts
Normal file
60
src/app/api/projects/route.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getDb } from '@/server/db';
|
||||
import { projects } from '@/server/db/schema';
|
||||
import { asc } from 'drizzle-orm';
|
||||
|
||||
export async function GET() {
|
||||
const db = getDb();
|
||||
|
||||
try {
|
||||
const result = await db
|
||||
.select()
|
||||
.from(projects)
|
||||
.orderBy(asc(projects.sortOrder));
|
||||
|
||||
return NextResponse.json(result);
|
||||
} catch (error) {
|
||||
console.error('Error fetching projects:', error);
|
||||
return NextResponse.json({ error: 'Failed to fetch projects' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const db = getDb();
|
||||
let body;
|
||||
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
|
||||
}
|
||||
|
||||
const { name, description = '', color = '#3b82f6' } = body;
|
||||
|
||||
if (!name?.trim()) {
|
||||
return NextResponse.json({ error: 'Name is required' }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
// Get max sort order
|
||||
const maxSort = await db
|
||||
.select({ max: projects.sortOrder })
|
||||
.from(projects)
|
||||
.limit(1);
|
||||
|
||||
const [newProject] = await db
|
||||
.insert(projects)
|
||||
.values({
|
||||
name: name.trim(),
|
||||
description: description?.trim() || '',
|
||||
color,
|
||||
sortOrder: (maxSort[0]?.max ?? -1) + 1,
|
||||
})
|
||||
.returning();
|
||||
|
||||
return NextResponse.json(newProject, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error('Error creating project:', error);
|
||||
return NextResponse.json({ error: 'Failed to create project' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user