Files
websitebuilder/src/app/api/organizations/route.ts
Kunthawat Greethong 4d1bb6892b
Some checks failed
CI / build (push) Has been cancelled
CI / test (push) Has been cancelled
CI / e2e (push) Has been cancelled
CI / lint (push) Has been cancelled
Add websitebuilder app
2026-01-26 12:50:12 +07:00

77 lines
2.3 KiB
TypeScript

import { requireAuth } from '@/lib/auth/middleware';
import { createOrganization, getUserOrganizations } from '@/services/organization.service';
import { type NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
// Validation schema for organization creation
const createOrganizationSchema = z.object({
name: z
.string()
.min(1, 'Organization name is required')
.max(255, 'Organization name is too long'),
slug: z.string().min(1).max(255).optional(),
});
/**
* GET /api/organizations - Get user's organizations
*/
export async function GET(request: NextRequest) {
try {
// Verify authentication
const authResult = await requireAuth();
if (!authResult.success || !authResult.user) {
return NextResponse.json(
{ error: authResult.error || 'Authentication required' },
{ status: 401 }
);
}
// Get user's organizations
const organizations = await getUserOrganizations(authResult.user.userId);
return NextResponse.json({ success: true, organizations }, { status: 200 });
} catch (error) {
console.error('Get organizations API error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
/**
* POST /api/organizations - Create new organization
*/
export async function POST(request: NextRequest) {
try {
// Verify authentication
const authResult = await requireAuth();
if (!authResult.success || !authResult.user) {
return NextResponse.json(
{ error: authResult.error || 'Authentication required' },
{ status: 401 }
);
}
// Parse request body
const body = await request.json();
// Validate input
const validationResult = createOrganizationSchema.safeParse(body);
if (!validationResult.success) {
return NextResponse.json(
{
error: 'Validation failed',
details: validationResult.error.issues,
},
{ status: 400 }
);
}
// Create organization
const organization = await createOrganization(authResult.user.userId, validationResult.data);
return NextResponse.json({ success: true, organization }, { status: 201 });
} catch (error) {
console.error('Create organization API error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}