-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandle-api-request.ts
More file actions
32 lines (29 loc) · 912 Bytes
/
handle-api-request.ts
File metadata and controls
32 lines (29 loc) · 912 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { HttpError } from '@api/errors/abstract/http-error';
import { StatusCodes } from 'http-status-codes';
import { NextResponse } from 'next/server';
export async function handleApiRequest<T>(
callback: () => Promise<T>,
successStatusCode?: StatusCodes
): Promise<NextResponse> {
try {
const data: Awaited<T> = await callback();
if (successStatusCode === StatusCodes.NO_CONTENT) {
return new NextResponse(null, { status: StatusCodes.NO_CONTENT });
}
return NextResponse.json(data, {
status: successStatusCode || StatusCodes.OK,
});
} catch (error) {
if (error instanceof HttpError) {
return NextResponse.json(
{ error: error.message },
{ status: error.status }
);
}
console.error(error);
return NextResponse.json(
{ error: 'Internal Server Error' },
{ status: StatusCodes.INTERNAL_SERVER_ERROR }
);
}
}