Passing variables to all modules - node.js

I'm building a service which is fragmented across multiple modules that are required when necessary.
I need to access the "request" variable from the router in all my modules.
My current solution (which has been suggested in other threads for passing variables in general) is to pass it to each required module:
var a_module = require('./a_module')(req);
And exporting each module as functions:
module.exports = function(req) {
...
}
But it is verbose and involves having to export my modules as functions, and only having access to this variable in the scope of the exported functions. Ideally I would like to be able to access the variable across the entire required module.
Is there any other elegant way to do it that I am missing? Like declaring the req variable as a global across the entire application?

This question is going to solicit opinions not answers, so it's not a great fit for stack overflow, but here's my $0.02.
You need to step back and ask yourself if you have really written so many modules that need access to a request object. I don't think you have. What you should be writing are functions that take the specific data they need - no more, no less. All these functions almost certainly don't need the entire request. How many of them really need access to every HTTP header, for example? Think of your program as a set of operations on domain objects/data. For example, maybe there's a function that takes a user account record and promotes it from a regular user to an administrator. All that function needs is the user account. It should not be coupled to an HTTP request object.
Just write a bunch of cleanly decoupled functions that take a small number of precise parameters and do something useful with them. This is called "loose coupling". Then organize groups of related functions into a module. This is called "cohesion". Then use some "glue" code to extract the necessary parameters from the HTTP req object and pass them as arguments to these functions. These same functions should work for a command line interface or another non-HTTP interface. They will be easier to understand, test, and more long-lived if you code them that way instead of going nuts with every line of every module knowing about the current HTTP req object.

Related

nestjs get method/function caller name or stack

I have a service that has a method (A.method()) which is called by other methods from multiple services (B.method(), C.method()...).
I want to know somehow what's the method caller name or the service that called my method.
The only working solution I found until know is throwing a dummy error and checking error.stack, but this is dirty :)
PS: I'm not using any controller/resolver, just functions that are starting because of cronjobs or constructors.
I tried interceptors & auth guards but it seems they do not work for simple methods.
I think the error stack is enough information.
If you find the name is ugly, then you should add sourceMap for better function name and file location.
Another approach ( maybe a bit overkill ) is to add tracing like Jaeger or OpenTelemetry to visualize the functions call, execution time and many other information.

Codesys DTU in library

We are working on a data logging code and I would like to make a library of it.
The only thing that different programs will need to define is the type strict for the sample that the want to save. The library will save a sample every x period. But I don't know exactly how to have an external DTU in the library code? Is possible to declare the DTU as an interface or something similar? There must be a way to do so but not so sure what it is.
CODESYS does not have generics, there is no way around that. Although I am not convinced it would be an elegant or fitting design, there is one way you might be able to do if you really want your type to be visible in your logging library, but it has serious drawbacks.
You can create another library, or more accurately a family of libraries that will all use the same placeholder. Each of these libraries can define a type of the same name. Reference this placeholder from your logging library, so that it will resolve the name. That will allow your library to compile. Then, by controlling which library the placeholder resolves to inside the project, you can select which type is used. The big downside is you cannot use your logging library with two different types inside the same project, as you cannot get a placeholder to resolve to two libraries at the same time.
Personally, I would probably implement the logging library with some sort of log entry writer as a function block that contains size + arrays of bytes and manages the details of actual logging, and then define inherited function blocks in projects/libraries that need logging. Each of these inherited function blocks would give access to the bytes in a typed way (method, exposed reference/pointer) and assign the size based on the data type used (SIZEOF in FB_Init, for instance). This requires a bit of code for each type, but really not much, and new types are easy to add with a 20-second copy+paste+modify.

Creating Similar Routes with Different Parameters in Nodejs

I did a google search, but I could not find what I really need.
I need to query an API, which have the same route, but with different parameters.
Example:
router.get('/items/:query, function(){})
In this case, I would search for all items
router.get('/items/:id, function(){})
Here, I would look for a specific item
At the core of your issue is that you are trying to specify two different resources at the same location. If you design your API to adhere to restful principles you'll see why that's not a wise choice. Here are two good starting points:
https://en.wikipedia.org/wiki/Representational_state_transfer
http://www.restapitutorial.com/lessons/whatisrest.html
In restful api's the root resource represents the item collection:
/api/items
...and when you specify an id that indicates you want only one item:
/api/items/abc123
If you really still want to accomplish what you asked in your question you'll need to add a url parameter like /items/query?query=true or /items/abc123?detail=true but this will be confusing to 99% of web developers who ever look at your code.
Also I'm not sure if you really meant this, but when you pass a variable named "query" to the server that seems to indicate that you're going to send a SQL query (or similar data definition language) from the client into the server. This is a dangerous practice for several reasons - it's best to leave all of this type of code on your server.
Edit: if you really absolutely positively have to do it this way then maybe have a query parameter that says ?collection=true. This would at least be understood by other developers that might have to maintain the code in future. Also make sure you add comments to explain why you weren't able to implement rest so you're not leaving behind a bad reputation :)
The issue is that without additional pattern matching there isn't a way Express will be able to distinguish between /items/:query and /items/:id, they are the same route pattern, just with different aliases for the parameter.
Depending on how you intend to structure your query you may want to consider having the route /items and then use query string parameters or have a separate /items/search/:query endpoint.

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.

is it acceptable to Require Node modules based on env var's or logic?

It might seem like an odd question but I am building a module that abstracts out certain logic for different data storage options. The Idea is that anyone using the module could use it with MongoDb or Redis or SQL or ( insert whatever option you want here )
I have a basic interface I am following in each of my implementations by exporting the same function names and signature just with different implementations for each of the various data storage options.
Right now I have a something like helper = require(process.env.data_storage_helper)
Then the helper can be used the same way.
Is this bad practise and if so why? Is there a better or suggested way to accomplish this kind of abstraction?
This isn't technically bad practice, but I would actually add a level of indirection. Instead, have those options stored in configuration files that get picked based on NODE_ENV or another environment variable. Then use the same key in the configuration object no matter what. A good example of a framework employing this is kraken.js, which auto-loads a configuration file based on NODE_ENV.
You can then grab a handle on the configuration object after Kraken has started up (or whatever you end up using - it uses confit under the hood - you can always just use this library directly), and you can grab the "data_storage_helper" key to see what your store is backed by within a storage module that does the decision making.
The big pro of this approach is that, now if you'd like to change the data storage or any other behavior of another module, you can just update a JSON file. :-)

Resources