-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapiResponse.ts
62 lines (54 loc) · 1.23 KB
/
apiResponse.ts
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
/**
* Reponse handlers
*
*/
import httpStatus from 'http-status'
import {ApiError} from './apiError'
import config from '../config'
interface SuccessResponse {
data: object
status: number
}
/**
* Send success response
*
* @param data: data that response sends to client
* @param created: whether new data is created or modified
* @param status: specific http status code that we want to send
*/
export const successResponse = (
data: string | object,
created?: boolean,
): SuccessResponse => {
const responseData = typeof data === 'string' ? {message: data} : data
let responseStatus = created ? httpStatus.CREATED : httpStatus.OK
return {
status: responseStatus,
data: responseData,
}
}
interface ErrorResponse {
status: number
errorCode: number
message: string
stack?: string
}
/**
* Send error response
*
* @param error error object passed from error handler middleware
*/
export const errorResponse = (error: ApiError): ErrorResponse => {
const {status, errorCode, message} = error
// Only return error stack if env is develop and status is 500
const stack =
config.isDev && status === httpStatus.INTERNAL_SERVER_ERROR
? error.stack
: undefined
return {
status,
errorCode,
message,
stack,
}
}