-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathresponse.ts
More file actions
67 lines (61 loc) · 2.25 KB
/
Copy pathresponse.ts
File metadata and controls
67 lines (61 loc) · 2.25 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
import type { Response } from 'express';
/**
* Standardized API response envelope.
*
* Every JSON response emitted by the API follows this shape so clients can
* branch on the presence of `error` rather than parsing free-form payloads.
* Exactly one of `data` / `error` is expected to be non-null at a time.
*/
export interface ApiResponse<T = unknown> {
/** Successful payload, or `null` when an error is present. */
data: T | null;
/** Human-readable error message, or `null` on success. */
error: string | null;
}
/**
* Sends a successful response with the unified envelope format.
*
* @param res The Express response object
* @param data The payload to send
* @param statusCode The HTTP status code (defaults to 200)
*/
export const ok = <T>(res: Response, data: T, statusCode = 200): Response => {
const payload: ApiResponse<T> = {
data,
error: null,
};
return res.status(statusCode).json(payload);
};
/**
* Sends a failure response with the unified envelope format.
* Prevents internal details from leaking by forcing generic messages for 500 errors
* unless a specific string message is provided.
*
* @param res The Express response object
* @param error The original error or error message
* @param statusCode The HTTP status code (defaults to 500)
*/
export const fail = (res: Response, error: unknown, statusCode = 500): Response => {
let errorMessage = 'Internal server error';
if (statusCode < 500) {
// For client errors (4xx), it's generally safe to send the message
if (typeof error === 'string') {
errorMessage = error;
} else if (error instanceof Error) {
errorMessage = error.message;
} else {
errorMessage = 'Bad request';
}
} else {
// For server errors (5xx), we strictly limit what we send
if (typeof error === 'string') {
errorMessage = error; // Only explicit strings are allowed to be sent for 5xx
}
// Note: We deliberately drop standard Error objects for 500 to avoid leaking internals like stack traces or SQL errors
}
const payload: ApiResponse<null> = {
data: null,
error: errorMessage,
};
return res.status(statusCode).json(payload);
};