-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathresponses.ts
More file actions
93 lines (84 loc) · 2.54 KB
/
Copy pathresponses.ts
File metadata and controls
93 lines (84 loc) · 2.54 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* Standardized API response utilities
*/
import { RateLimitError } from "../services/rate-limit/errors";
import { SecurityError, SecurityErrorType } from 'shared/types/errors';
/**
* Standard response shape for all API endpoints
*/
export interface BaseErrorResponse {
message: string;
name: string;
type?: SecurityErrorType;
errorType?: string;
exceededLimits?: Array<{
type: string;
window: string;
current: number;
max: number;
percentUsed: number;
}>;
hasUserToken?: boolean;
}
export interface RateLimitErrorResponse extends BaseErrorResponse {
details: RateLimitError;
}
type ErrorResponse = BaseErrorResponse | RateLimitErrorResponse;
export interface BaseApiResponse<T = unknown> {
success: boolean;
data?: T;
error?: ErrorResponse;
message?: string;
}
/**
* Creates a success response with standard format
*/
export function successResponse<T = unknown>(data: T, message?: string): Response {
const responseBody: BaseApiResponse<T> = {
success: true,
data,
message,
};
return new Response(JSON.stringify(responseBody), {
status: 200,
headers: {
'Content-Type': 'application/json'
}
});
}
/**
* Creates an error response with standard format
*/
export function errorResponse(error: string | Error | SecurityError, statusCode = 500, message?: string): Response {
let errorResp: ErrorResponse = {
message: error instanceof Error ? error.message : error,
name: error instanceof Error ? error.name : 'Error',
}
if (error instanceof SecurityError) {
errorResp = {
...errorResp,
type: error.type,
}
}
// Include usage limit error details if present
if (error && typeof error === 'object' && 'errorType' in error) {
const errorObj = error as Error & { errorType?: string; exceededLimits?: BaseErrorResponse['exceededLimits']; hasUserToken?: boolean };
errorResp = {
...errorResp,
errorType: errorObj.errorType,
exceededLimits: errorObj.exceededLimits,
hasUserToken: errorObj.hasUserToken,
}
}
const responseBody: BaseApiResponse = {
success: false,
error: errorResp,
message: message || (error instanceof Error ? error.message : 'An error occurred'),
};
return new Response(JSON.stringify(responseBody), {
status: statusCode,
headers: {
'Content-Type': 'application/json'
}
});
}