source: src/app/api/tenant/route.ts@ 299af01

main
Last change on this file since 299af01 was 299af01, checked in by Naum Shapkarovski <naumshapkarovski@…>, 6 weeks ago

chore

  • Property mode set to 100644
File size: 2.1 KB
Line 
1import { NextRequest, NextResponse } from 'next/server';
2import prisma from 'src/lib/prisma';
3import { tenantSchema } from 'src/schemas';
4import { z } from 'zod';
5import { authenticateRequest } from 'src/lib/auth-middleware';
6
7export async function GET(request: NextRequest) {
8 try {
9 const auth = await authenticateRequest(request);
10 if (auth instanceof NextResponse) {
11 return auth; // Return error response if authentication failed
12 }
13 const { tenantId } = auth;
14
15 const tenant = await prisma.tenant.findUnique({
16 where: { id: tenantId },
17 });
18
19 if (!tenant) {
20 return NextResponse.json({ error: 'No tenant found' }, { status: 404 });
21 }
22
23 return NextResponse.json(tenant);
24 } catch (error) {
25 console.error('Error fetching tenant:', error);
26 return NextResponse.json({ error: 'Failed to fetch tenant' }, { status: 500 });
27 }
28}
29
30export async function POST(request: NextRequest) {
31 try {
32 const auth = await authenticateRequest(request);
33 if (auth instanceof NextResponse) {
34 return auth;
35 }
36 const { tenantId } = auth;
37
38 const body = await request.json();
39
40 // Validate request body
41 const validatedData = tenantSchema.parse(body);
42
43 // Check if tenant already exists
44 const existingTenant = await prisma.tenant.findUnique({
45 where: {
46 id: tenantId,
47 },
48 });
49
50 if (existingTenant) {
51 return NextResponse.json({ error: 'Tenant already exists' }, { status: 400 });
52 }
53
54 // Create new tenant with the authenticated tenantId
55 const tenant = await prisma.tenant.create({
56 data: {
57 ...validatedData,
58 id: tenantId, // Ensure the tenant is created with the authenticated tenantId
59 },
60 });
61
62 return NextResponse.json(tenant, { status: 201 });
63 } catch (error) {
64 if (error instanceof z.ZodError) {
65 return NextResponse.json(
66 { error: 'Invalid request data', details: error.errors },
67 { status: 400 }
68 );
69 }
70
71 console.error('Error creating tenant:', error);
72 return NextResponse.json({ error: 'Failed to create tenant' }, { status: 500 });
73 }
74}
Note: See TracBrowser for help on using the repository browser.