JSFiddle - React, Tailwind, and code Playground
JavaScript
class Response {
/**
* Represents a Response
* @constructor
* @param {int} statusCode - Response code
* @param {object} body - Response body
*/
constructor() {
this.statusCode = 204;
this.body = null;
}
/**
* Set the response code
* @param {int} statusCode - Response code
* @return {Response}
*/
status(statusCode) {
this.statusCode = statusCode;
return this;
}
/**
* Set the response code
* @param {object} body - Response body
* @return {Response}
*/
body(body) {
this.body = JSON.stringify(body);
return this;
}
/**
* Sets the key to 'error' when an error occured
* @param {object} error - Error response body
* @return {Response}
*/
error(error) {
this.body = JSON.stringify({
error: error,
});
return this;
}
/**
* Returns a Response with a status code and stringified response body
* @return {Response}
*/
build() {
return {
statusCode: this.statusCode,
body: this.body,
};
}
}
new Response().status(200).body('test').build()