1+ // standardized API response format
2+ import Constants from "../constants.js" ;
3+
4+ class ApiResponse {
5+ constructor ( status , message , data = null , errorType = 'UNSPECIFIED' , error = null ) {
6+ this . success = status < 300 ? true : false ; // Boolean value indicating whether the request was successful or not
7+ this . message = message , // Brief description of the result
8+ this . data = data || null , // Contains the actual response data (if any)
9+ this . status = status || 200 // HTTP status code
10+
11+ // If the environment is development, include the error details in the response
12+ // POLICY DECISION ?? Only include error details in response if in development mode
13+ if ( ! this . success ) {
14+ this . error = Constants . ENV === 'development' ? error : null ;
15+ this . errorType = Constants . ENV === 'development' ? errorType : null ;
16+ }
17+
18+ // Log the response details to the console
19+ // DEVELOPMENT ONLY
20+ if ( Constants . ENV === 'development' ) {
21+ console . log ( "[API RESPONSE START]" ) ;
22+ console . log ( `[API RESPONSE] ${ this . success ? 'SUCCESS' : 'FAILURE' } ` ) ;
23+ console . log ( `[API RESPONSE] STATUS: ${ this . status } ` ) ;
24+ console . log ( `[API RESPONSE] MESSAGE: ${ this . message } ` ) ;
25+ console . log ( "[API RESPONSE] DATA:-" ) ;
26+ console . dir ( this . data ) ;
27+ if ( ! this . success ) {
28+ console . log ( "[API RESPONSE] ERROR:-" ) ;
29+ console . dir ( this . error ) ;
30+ console . log ( `[API RESPONSE] ERROR TYPE: ${ this . errorType } ` ) ;
31+ }
32+ console . log ( `[API RESPONSE] TIMESTAMP: ${ new Date ( ) . toISOString ( ) } ` ) ;
33+ console . log ( "[API RESPONSE END]" ) ;
34+ }
35+ }
36+ }
37+
38+ // Helper functions to send API responses
39+ /** successResponse(res, data, message) => void */
40+ const successResponse = ( res , data , message ) => {
41+ res . status ( 200 ) . json ( new ApiResponse ( 200 , message , data ) ) ;
42+ }
43+
44+ /** successResponseWithCookies(res, data, message, cookies) => void */
45+ const successResponseWithCookies = ( res , data , message , cookies ) => {
46+ const options = { httpOnly : true , secure : true , sameSite : "strict" } ;
47+
48+ if ( cookies ) {
49+ if ( cookies . accessToken ) {
50+ res
51+ . status ( 200 )
52+ . cookie ( "accessToken" , cookies . accessToken , options )
53+ . json ( new ApiResponse ( 200 , message , data ) ) ;
54+ }
55+ if ( cookies . refreshToken ) {
56+ res
57+ . status ( 200 )
58+ . cookie ( "refreshToken" , cookies . refreshToken , options )
59+ . json ( new ApiResponse ( 200 , message , data ) ) ;
60+ }
61+ }
62+ }
63+
64+ /** errorResponse(res, status, message, errorType, error) => void */
65+ const errorResponse = ( res , status , message , errorType , error ) => {
66+ res . status ( status ) . json ( new ApiResponse ( status , message , null , errorType , error ) ) ;
67+ }
68+
69+ export { successResponse , errorResponse , successResponseWithCookies } ;
0 commit comments