I've read several times that a singleton should be avoided as much as possible. By singleton I mean this kind of code
exports = module.exports = new Passport();
This code is from the Node.js module PassportJS. It allows us to use passport and add some var that will be shared inside our entire code.
So as you can see we can make this code:
https://github.com/ragulka/sails-starter-app/blob/master/api/controllers/SessionController.js
(This is just an example, I do too and I blame no one).
Note that he is taking passport at the top of the file with require and then using one of the strategies that have been added previously in the code. Obviously it's convenient but is it the best way to do this?
Is there no way to pass passport variable inside controllers from previous code?
Let me know if something is not clear.
Thanks in advance.
There are cases like this, a passport instance, an express app instance, a mongodb connection pool, a logger instance, etc, where the most common case is a single instance per node process. In these situations, a singleton can be convenient and keep code concise, provided the module also provides an easy way to access and call the constructor for those minority times you want more than one instance (like if your app wants to 2 distinct pools of connections to 2 distinct mongodb databases, or 2 different log streams, for example).
This can sometimes be inconvenient for testing, mocking, stubbing, etc, though.
Is there no way to pass passport var inside controllers from previous code ?
Yes, there is. When you do var passport = require("passport"); you will always get back the exact same singleton instance, including all it's internal state as configured by other code in your application. This is due to the caching that happens in the node require call. What takes extra code is if you want to create a new distinct Passport instance, in which case you need to call the constructor yourself.
Related
I am trying to store a socket created for the client in App.js in my Redux store? I am not sure if this is even a good idea or not, but I want to be able to access the same socket in multiple components, so I thought I could just do it like I did with other objects.
Howerever, the things I stored until now in my redux store are strictly objects with fields in them, I have never stored an object that had functions.
When I try to call a function of the stored socket, I get:
TypeError: this.props.socket.emit is not a function.
Which I guess means that I can't store class entities using Redux. Is this correct?
What would be the right solution here?
The best method to do something like this would be to isolate all code that deals with sockets and expose only those functions that your components call (something like socket.send(message: string) to send message etc).
Don't worry about importing the same module/file again and again, as no matter how many times you import/require it, the same instance is returned. So it's safe to isolate the socket functions and import them wherever needed.
Also, Redux is a state management library, therefore please don't expect it to handle functions and other advanced functionality.
I am quite sure that I am not the first person on the planet trying to implement the following, but I am sure that I am not able to find a good guide how to do it.
Our node backend is setup quite like a MVC to say so.
View = Express Server offering our api
Controller = Library, a set of controller functions to manage our data
Model = Our mysql database, it's Javascript DAO respectively (since our usecase is quite unique we need to write own DAO's and can not go let's say for js-data.
The challenge we face now, is:
As a developer, I want to keep our library clean from overhead for developers.
On the other side, as a database administrator I clearly want to know who did what modification and so on
Until now I tried to keep the 'user' object out of the library, since I do not want all controller functions to look like
function ctrl(param1, param2, param..., user)
Going for this would mean, we have to pass around User objects all the time, which would make it a pain to code inside the libraries.
On the other hand, I can not find any other approach in node/express to somehow get knowledge about the user without passing it (since we do not really have sessions, at least not yet in our code).
TL:DR; I do want to action log all database modifications, but do not want to pass around a User object all the time.
Is there any known approach for that challenge which does scale and is 'best practice'?
Thanks in advance
We are struggling now with NodeJS, as we don't want to pass some general request based data through lots of callbacks. We have multiple async calls, changed, updates in one remote method and we need to be able to extract the sessionId and customerId on every step without passing them as parameters to every function. Here is what we tried:
Writing to the "app" object is not secure and is overridden by multiple simultaneous request.
Writing to the "ctx.req" object doesn't change anything, as then you need to pass the "req" object to all callbacks.
Is there a good way to work with kind of request based context, that you can use everywhere in the application or you still need to pass some variable everywhere?
Node.js is best for implementing stateless servers. I don't know your codebase and architecture. But I guess you need to use a persistence store like
Redis or Memcached or Firebase(service)
with a token for each session. And use this token to grab the objects from persistence store. This is a pretty standard approach while implementing stateless servers. Firebase provides the added advantage of realtime updates and even completely bypassing the server if required.
You may have to show some code and design for a more improved answer.
You can use the javascript merit like Ex:
var topFunction={
firstFunction:function(){
console.log(id);
------//work you want to do
},
secondFunction:function(){
console.log(id);
---//work you want to do
}
}
function test(){
var arr=[2,3,4,5,6,7];
topFunction.id=10;
async.map(arr,topFunction.firstFunction.bind(topFunction),function(err,result){
})
You got every time the same id in async call it is best way to use the the async call .You do't need to send the the id again and again .You can use this feature of javascript as context in request.The value of id different for every req
If I wanted to utilise useful middleware like express.cookieParser(); and suchlike, am I expected to be economical with my instances of express when splitting my NodeJS application up into different files.
For example, if I use var express = require('express') in one file, and again in many others, am I wasting resources fetching these and re-instantiating them? Or does require cache modules, or (even better) create a global instance of them?
I know the performance impact of requiring express on multiple files would probably be negligible - this is more of a question to help me understand how modules load.
When you require a module twice, the second require uses the cached exports object that was called earlier.
Source: http://docs.nodejitsu.com/articles/getting-started/what-is-require
I'm using express and I want to put some configurations in a file(like database configuration, api credentials and other basic stuffs).
Now I'm putting this configuration in a JSON and I read this file using readAsync.
Reading some code I noted a lot of people use don`t use a JSON.. Instead, they use a common JS file and exports in a module.
Is there any difference between these approaches, like performace?
The latter way probably simplifies version control, testing and builds, and makes it easier to have separate configurations for production and development. It also lets you do a little "preprocessing" like defining "constants" for common setups.
In a well-designed application, the performance of configuration-reading is going to be completely irrelevant.
If you go with the latter, you need to practice some discipline: a configuration module should consist almost entirely of literals, with only enough executable code to handle things like distinguishing between development and production. Beware of letting application logic creep into it.
In node.js require works synchronously, but it's not very important if you load configurations once on the application starts. Asynchronously way realy need only if you loading configurations many times (for each request for example).
In node.js you can simply require your json files:
config.json:
{
"db": "127.0.0.1/database"
}
app.js:
var config = require('./config');
console.log(config);
If you need something more full featured I would use flatiron/nconf.