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
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 looking at developing a solution with Dialogflow, where the User Interface events (e.g. Typed user input) are going to arrive as http REST events.
The problem with this is that the Dialogflow Client API (Note: This is NOT THE SAME THING as the fulfilment API), looks like it is stateful: https://github.com/googleapis/nodejs-dialogflow
(... But I could be wrong on that...)
And stateful is hard in most (all?) modern serverless paradigms that any sane person is probably using. Mainly - There is no gaurantee that subsequent events will arrive at the same run-time instance.
It's a bit infuriating that although many examples are supplied at the repo above, none of them look like realistic (but small) applications, handling multi-session, multi-turn (even 2-3 turns) user input.
Is the idea that any run-time instance could/would call new dialogflow.SessionsClient(); just once PER RUNTIME initialisation (NOT per session) to initialise the API, and then everything else is done via like await sessionClient.detectIntent(request); ???
Now that I've typed this, I am pretty confident that is right. But if anyone could confirm it would be great!
The underlying Dialogflow Session API itself is stateless - any statefull decisions that are made must be included in your call to detectIntent. The JavaScript library reflects this stateless scenario as well.
The SessionsClient constructor sets up the connection and authentication information, but does not maintain any other conversational state. So you can use the same object to manage multiple conversations.
Note that this still means you need to maintain conversational state (the session id, the values and lifespans returned in contexts, etc) in order to pass it to detectIntent as part of the request.
I have to create a middleware API which a functionality to check for a key present in my database. If the key exists then it should simply fetch it(GET method). If not, then the API should create the key and its value in the database and return that(POST method). So since we have 2 fundamentally different methods being combined in this API, is it correct to do so? What should be the best way to design such API?
Don't combine them.
Return zero results from your GET method if you the record doesn't exist. Then in the client, if you receive zero results, POST the needed information to another API endpoint.
Combining the two ideas into one will create a hard to understand system. Your system should be deterministic, i.e. you can always know the result of every call before you call it.
One way to look at your API is to forget about the underlying database, but think about how an API client uses it.
If an API client does a GET request, 2 things happen:
The existing record is returned
A new record is created and is returned
A client might not actually care if 1 or 2 happened. For the perspective of the client, it might look like the resource always existed (even if it was technically just created).
So as long as there's no extra information that must be sent along with a POST request, it might be fine to use a GET request for both cases.
I don't know about your situation, typically it is best to have your get and post seperated. Though, if your client thinks that it needs to create a record and then posts the data, i dont see the problem with returning the resource and a 409 for the resource already existing. Here is a similar question HTTP response code for POST when resource already exists
Then the client can handle the 409 differently or the same as a 200 depending on your needs.
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
I have noticed that in order to store a value into the session you simply call
req.session.key = value
without the need to specify a callback. I have set mysql as my session storage adapter using the connect-mysql module. So I am wondering that consider each time I save a value to the session it is being updated in the db, shouldn't there be a callback associated with this? Yet everywhere I look people are happily using it synchronously. Can someone please explain why this is the case? THanks.
The session middleware only actually interacts with the data-store twice per request, rather than immediately with each change:
With Store#get() to retrieve the Session in bulk at the start of a request. (source)
With Store#set() (via Session#save()) to persist the Session in bulk at the end of the request. (source)
Between these steps, changes to the session can be done synchronously. They just should be done before res.end() or similar (res.render(), res.json(), etc.) is called.