-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandle-api-request.ts
More file actions
45 lines (42 loc) · 1.47 KB
/
handle-api-request.ts
File metadata and controls
45 lines (42 loc) · 1.47 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
import { HttpError } from '@shared/errors/http-error';
import { StatusCodes } from 'http-status-codes';
import { NextResponse } from 'next/server';
import type { HttpResponseDto } from '@shared/dto/output/responses/abstract/http.response.dto';
import { ApiLogger } from '@api/logs/api.logger';
import { InternalServerError } from '@api/errors/http/internal-server.error';
import { BusinessError } from '@shared/errors/business-error';
export async function handleApiRequest<Data>(
callback: () => Promise<Data>,
successStatusCode?: StatusCodes
): Promise<NextResponse<HttpResponseDto<Data>>> {
try {
const data: Awaited<Data> = 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: unknown) {
let httpError: HttpError;
if (error instanceof HttpError) {
httpError = error;
if (error instanceof BusinessError) {
return NextResponse.json(
{ error: { message: httpError.message, code: error.code } },
{ status: httpError.status }
);
}
} else {
ApiLogger.error('Error while handling API errors: ', error);
httpError = new InternalServerError();
}
return NextResponse.json(
{ error: { message: httpError.message } },
{ status: httpError.status }
);
}
}