Created
November 27, 2022 12:22
-
-
Save robert-kratz/839bdcc685cd8a3bb5c3e4a2aed7c22d to your computer and use it in GitHub Desktop.
NodeJS Express response formatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = class Response { | |
constructor(response) { | |
this.code = response.statusCode; | |
this.date = new Date(); | |
this.error = []; | |
this.data = {}; | |
return this; | |
} | |
/** | |
* Set the message which will be displayed in the response | |
* @param {String} message | |
* @returns Response | |
*/ | |
setMessage(message) { | |
this.message = message; | |
return this; | |
} | |
/** | |
* Adds an error to the response | |
* @param {String} error | |
* @param {String} message | |
* @default code = '' | |
* @returns Response | |
*/ | |
addError(error, message = -1) { | |
this.error.push({code: error, id: message}); | |
return this; | |
} | |
/** | |
* Adds data to the response | |
* @param {Object} key | |
* @param {Object} value | |
* @returns Response | |
*/ | |
addData(key, value) { | |
this.data[key] = value; | |
return this; | |
} | |
/** | |
* Returns the response as an json object | |
* @returns Object | |
*/ | |
init() { | |
return ({ | |
code: this.code, | |
date: this.date, | |
message: this.message || '', | |
data: this.data, | |
error: this.error, | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment