how to implement postprocess filtering of response as middleware in node? - node.js

As part of authorization-rules I'd like to centralize logic as to what fields of a json-response are returned to the user.
To me, it makes sense to somehow implement this as some sort of postprocess-filter implemented in node-middleware.
Apart from the question whether it's considered good practice to change the output of a REST-endpoint based on some authorization-rules (I'm not sure, please share if you've got a strong opinion), I'm uncertain how to implement such a post-process filter.
I tried to implement it by listening to response.finish and have the filter kick in, but that's too late. i.e.: the response was already send.
Instead, what would be considered best practice for post-processing responses in Node?

you can perform your data operations at any part of communication chain, so if require to do some post data filter you can do your CRUD operations in a middle ware and then filter it in other step something like
AUTHENTICATION-(next)->AUTHORIZATION-(next)->OPERATIONS-(next)->LIMITS-(next)->RESPONSE
where each step except RESPONSE reffers to a middleware that will alter the request object with the pertinent information to pass to the next middleware

Related

Should I use a nestjs pipe, guard or I should go for an interceptor?

Well I have a few pipes in the application I'm working on and I'm starting to think they actually should be guards or even interceptors.
One of them is called PincodeStatusValidationPipe and its job as simple as snow. It checks the cache for a certain value if that value is the one expected then it returns what it gets otherwise it throws the FORBIDEN exception.
Another pipe is called UserExistenceValidationPipe it operates on the login method and checks if a user exists in DB and some other things related to that user (e.g. wheter a password expected in the login method is present and if it does then whether it matches that of the retrieved user) otherwise it throws appropriate exceptions.
I know it's more of a design question but I find it quite important and I would appreciate any hints. Thanks in advance.
EDIT:
Well I think UserExistenceValidationPipe is definitely not the best name choice, something like UserValidationPipe fits way better.
If you are throwing a FORBIDEN already, I would suggest migrating the PincodeStatusValidationPipe to be PincodeStatusValidationGuard, as returning false from a guard will throw a FORBIDEN for you. You'll also have full access to the Request object which is pretty nice to have.
For the UserExistenceValidationPipe, a pipe is not the worst thing to have. I consider existence validation to be a part of business logic, and as such should be handled in the service, but that's me. I use pipes for data validation and transformation, meaning I check the shape of the data there and pass it on to the service if the shape looks correct.
As for interceptors, I like to use those for logging, caching, and response mapping, though I've heard of others using interceptors for overall validators instead of using multiple pipes.
As the question is mostly an opinionated one, I'll leave the final decision up to you. In short, guards are great for short circuiting requests with a failure, interceptors are good for logging, caching, and response mapping, and pipes are for data validation and transformation.

Which layer should I use to factorize the existence checking of a ressource?

I'm trying to factorize the fact that for all routes that are similar to : /ressources/:id/* we should always check the ressource existence.
I'm not sure how to do it the proper NestJS.
Should I use a middleware, a guard or even pipes (it can be seen as a kind of validation) ?
Hope my question is clear enough,
Thanks in advance
I would say that a pipe is a proper spot in this case, as a guard will return a 403 and a middleware runs the query to your database before you've authenticated the request. You can also use DI in the pipe to make the queries to the database easier, and use the pipe only on the body or request param, depending on how you want to handle things.

Send one of multiple parameters to REST API and use it

I use MEAN stack to develop an application.
I'm trying to develop a restful API to get users by first name or lastname
Should I write one get function to get the users for both firstname and lastname?
What is the best practice to write the URL to be handled by the backend?
Should I use the following?
To get user by firstname: localhost:3000/users?firstname=Joe
To get user by name:localhost:3000/users?firstname=Terry
And then check what is the parameter in my code and proceed.
In other words,What is the best practice if I want to pass one of multiple parameters to restful API and search by only one parameter?
Should I use content-location header?
There is no single best practice. There are lots of different ways to design a REST interface. You can use a scheme that is primarily path based such as:
http://myserver.com/query/users?firstname=Joe
Or primarily query parameter based:
http://myserver.com/query?type=users&firstname=Joe
Or, even entirely path based:
http://myserver.com/query/users/firstname/Joe
Only the last scheme dictates that only one search criteria can be passed, but this is likely also a limiting aspect of this scheme because if you, at some time in the future, want to be able to search on more than one parameter, you'd probably need to redesign.
In general, you want to take into account these considerations:
Make a list of all the things you think your REST API will want to do now and possibly in the future.
Design a scheme that anticipates all the things in your above list and feels extensible (you could easily add more things on to it without having to redesign anything).
Design a scheme that feels consistent for all of the different things a client will do with it. For example, there should be a consistent use of path and query parameters. You don't want some parts of your API using exclusively path segments and another part looking like a completely different design that uses only query parameters. An appropriate mix of the two is often the cleanest design.
Pick a design that "makes sense" to people who don't know your functionality. It should read logically and with a good REST API, the URL is often fairly self describing.
So, we can't really make a concrete recommendation on your one URL because it really needs to be considered in the totality of your whole API.
Of the three examples above, without knowing anything more about the rest of what you're trying to do, I like the first one because it puts what feels to me like the action into the path /query/users and then puts the parameters to that action into the query string and is easily extensible to add more arguments to the query. And, it reads very clearly.
There are clearly many different ways to successfully design and structure a REST API so there is no single best practice.

posting to same URL but using 2 different functions

a portion of my application involves creating tests (i.e., picking x-number of questions from a filtered set of questions). The user is able to determine how big they want the test but to do so I need to calculate on the server how many questions are available. The function which creates the test is sent through this post:
app.post('/user/create_test', users.create_test);
As the user changes filters, I would like to determine the number of questions available... All I can think of is to use AJAX post to send the filter information but it will be passed to the same function as creating a test would... is there any way to post to the same URL but determine which function you execute?
Consider creating another function. - The best way to do Restful API's.
Consider renaming to app.post('/user/test').
The second function could be app.post('/user/test/filters').
Or make a single POST request and make sure your function does both creating and filtering.
In general, the design of the app lacks maturity. Rethink the client-server communications.

Returning a Status from the Domain

In our domain-driven application, we use a type called ServiceResponse<> to send data between layers of our application - specifically, one is returned by every method in the domain. As of right now, it encapsulates the data (if any) which was returned from the method, or any errors that it may have generated.
My question, then, is this: is it an acceptable practice to add fields to this object that may be useful in other layers of the application? For example, is it good form to add a Status or StatusCode field to it that may be interpreted later by the service layer for use as an HTTP status code (with or without some mapping)?
It sounds like a fine place to me. The idea that every method returns a "response" of some sort smells a bit like trying to decouple too much, but there are some cases where such extreme decoupling is warranted.
In any case, the ServiceResponse could easily have a status, and if it needed one, that is where I would put it.

Resources