1. Install
npm i @toorieaa/httpacceptable
2. Import
import HttpAcceptable from "@toorieaa/httpacceptable";
3. How is it implemented?
import SingletonClassError from "@toorieaa/singletonclasserror";
export default class HttpAcceptable {
static ANYTHING_IS_FINE = "*/*";
static APPLICATION_JSON = "application/json";
static TEXT_HTML = "text/html";
constructor() {
throw new SingletonClassError();
}
}
4. Use cases
Sometimes when building an application endpoint, you only need to serve just text/html and application/json and anything for the case of web forms
5. Examples
Examples of where we may use this
- A snippet from an node/express with ecma support... endpoint. HttpStatus is another independent library. More on that here https://www.npmjs.com/package/http-status
const errorMessage = `username / password should be specified and greater than ${usernameShouldBeAtLeastLength} / ${passwordShouldBeAtLeastLength} respectively`;
const errorObjectForJsonResponses = {
status: HttpStatus.getStatusText(HttpStatus.BAD_REQUEST),
message: errorMessage,
};
if (headers._acceptableResponse === HttpAcceptable.ANYTHING_IS_FINE) {
response.status(HttpStatus.BAD_REQUEST).json(errorObjectForJsonResponses);
return;
}
if (headers._acceptableResponse === HttpAcceptable.TEXT_HTML) {
response.status(HttpStatus.BAD_REQUEST).send(errorMessage);
return;
}
if (headers._acceptableResponse === HttpAcceptable.APPLICATION_JSON) {
response.status(HttpStatus.BAD_REQUEST).json(errorObjectForJsonResponses);
return;
}
5.1. License
[MIT]