Contacting a Boca Raton truck accident lawyer after a truck accident, semi-truck, or tractor-trailer accident should be done soon after seeking medical treatment. While any motor vehicle accident can…
Content Negotiation according to the MDN documentation is:
What this simply means is when implemented in your application, you can utilize the same URL or endpoint to serve up either HTML, JSON, XML etc.
I enjoy using Content Negotiation because it allows for a quick turn-around if I want to build a system that serves up HTML views as well as a structured API response in JSON format.
Enter AdonisJS
The AdonisJS official website describes the NodeJS framework as follows:
I have to say I can testify to this statement, I absolutely love this NodeJS framework and it makes creating web applications and APIs so much fun.
This is the example from the AdonisJS documentation
It works perfectly, however, I have come across numerous articles that speak about the additional complexities that switch statements can create in your application.
Personally, I have nothing against the switch statement and it makes a feature every now and then in my codebase but in the context of content negotiation, I personally feel like this is repetitive and I wanted to see if I could abstract this into one or two functions to make it cleaner and thus more reusable across an entire application.
I set to work doing just that and remember AdonisJS v5 is built with Typescript so I ended up with the following:
My version of the example above became this:
The payloadGeneratorForViewAndApi
Function
This function basically creates the structure of the payload I need to pass to the function that handles the content negotiation activity.
It takes in the following parameters:
The viewAndApiOutputHelper
Function
This is the main function that does the heavy lifting. It takes in the following parameters:
The Interfaces & Custom Type
The interfaces and custom type used by the viewAndApiOutputHelper
are exported from a single file called, viewAndApiOutputInterfaces
This implementation provides an easy and extensible implementation that can be reused not just in one project but any project within which you intend to utilize Content Negotiation.
I hope you found this useful.
On day six of my trip, I planned to visit Saint Petersburg by bike with Olga. My day started at her hostel since the night before I couldn’t go back to my host(Luba). She told me about her plan and I…
If you live in an old home, there’s a good chance that the walls are made of horse hair plaster. While this plaster is durable and long-lasting, it can become damaged or cracked over time. If you’re…
The term Artificial Intelligence (AI) has become ubiquitous in today’s world and its influence can be felt across various industries and sectors. AI refers to the development of computer systems that…