Express / Mongoose REST and middleware - node.js

If you apply middleware to a rest POST call and you provide an array of JSON objects as the req.body will the middleware iterate through each object and run for each one or will it just run once for the entire request body?

Ended up having to write my middleware in a way that can handle arrays and iterate through by using: for ( var i in req.body ) {...}.
There is no documentation on this and down voting for no research effort is asinine.
The answer is in fact that it only runs once for the request even if you provide an array. Hope this answer is helpful for someone else..

Related

Should I store a very long array in back-end or front-end?

In my angular application, I have a very long array and would like to put it some where I could access very easily from my front-end don't slow down my application, there are multiple options and I don't which one is the best. Should I store it in:
my API
app.get('models', (req, res) =>{var models = ['m1', 'm2', 'm3', ..., 'mn'];
res.send(models);
});
In API DB:
app.get('models', (req, res) =>{
Models.find({}, (dara, err){
res.send(models);
})
});
in my front-end:
// models.ts
in a variable in my component
any comment will be appreciate.
The answer depends on what you want to do, so:
In the Frontend
Is never a good idea try to have data on your frontend, this implicates that the user will request for a full list of data that will only use or read a few.
If you still consider that you wanna do it there: You can have always in a constant, then you can consume that using local storage(be careful with the space limitation 10MB), global variables or just a file to import
Note: Using suspense or any lazy loading you will be able to avoid sending this data at the same time that everything else.
In the Backend
Yes, is the best place to have information that you need to request, there you can use a DB to store and a GET to request it is the common and best approach.
Note: Avoid send all the list in one request in you can, try indexing or use pagination, for most of the cases you don't need have such big arrays on FE.
But at the end, is more a decision based on what you want to build that only one good answer.
Hope this helps you!

NodeJs: Socket.io use() method

I can't find any document that make an understanding about use() method. Please explane socket.use() method.
Thanks a lot
socket.use() is basically where you can add middleware functions, which just means that the function passed as the parameter for thesocket.use() function is executed for every piece of info received.
Here's the socket.io docs
https://socket.io/docs/server-api/#socket-use-fn
socketio.use() method is same like as express_app.use() method , means both are used for passing middleware-functions , where middleware-functions can control/manipulate every upcoming requests/response on the server.

multiple requests in one URLusing expressJS

I am using Express with Node and I have a requirement in which the user can request the URL as: http://myhost/api/add?mid="mid01"/userID
and I tried this
app.get('/api/:myMedia/:id', function (req, res){
...
})
and tried these req.query for getting mid01 and it didn't work.
I want to have req.params.id and req.query together. How can I handle this?
If your requirement really is http://myhost/api/add?mid="mid01"/userID, it might be a good idea to change that requirement, because it seems really not the right way to do something
But if you really want to do that you should declare your route like app.get('/api/add', ...)
Then with req.query.mid you can get your query value which is "mid01"/userID
Finaly it's up to you to parse that query value to do what you want
But you should not use URL like that, if possible try to use URL in a more standard way, http://myhost/api/add/userID?mid=mid01 or http://myhost/api/add?mid=mid01&path=/userID
To chain requests, use &. http://myhost/api/add?foo1="bar1"&foo2="bar2". This way both of the queries will show up.

Replacement for req.param() that is deprecated in Express 4

We are migrating from ExpressJS 3 to ExpressJS 4, and we noted that the following APIs are being deprecated:
req.param(fieldName)
req.param(fieldName, defaultValue)
Is there a middleware that brings these APIs back, like other APIs that were 'externalized' from express to independent modules ?
EDITED:
Clarification - The need is an API that provides an abstracted generic access to a parameter, regardless to if it is a path-parameter, a query-string parameter, or a body field.
Based on Express Documentation, we should use like this
On express 3
req.param(fieldName)
On express 4
req.params.fieldName
Personally i prefer req.params.fieldName instead req.param(fieldName)
Why would you want to bring it back? There's a reason that it's been deprecated and as such you should probably move away from it.
The discussion on why they are deprecating the API is available at their issue tracker as #2440.
The function is a quick and dirty way to get a parameter value from either req.params, req.body or req.query. This could of course cause trouble in some cases, which is why they are removing it. See the function for yourself here.
If you are just using the function for url parameters, you can just replace it with this a check for req.query['smth'] or 'default':
var param_old = req.param('test', 'default');
var param_new = req.query['test'] || 'default';
(Please note that an empty string is evaluated to false, so they are not actually 100% equal. What you want is of course up to you, but for the most part it shouldn't matter.)
Ok, after reading the threads given in references by #Ineentho, we decided to come up with the following answer:
https://github.com/osher/request-param
A connect/express middleware to enable back the req.param(name,default) API deprecated in express 4
The middleware does not only brings back the goo'old functionality.
It also lets you customize the order of collections from which params are retrieved , both as default rule, and as per-call :-)
Have fun!

Expressjs one function to handle GET and POST

Is it is better to have a separate function to handle GET and POST requests for the same API endpoint or combine them into one function that discriminates based on the existence of req.body or req.params?
ie.
app.get('/api/profilepic', api.get_profilepic);
app.post('/api/profilepic', api.change_profilepic);
or:
app.get('/api/profilepic', api.profilepic);
app.post('/api/profilepic', api.profilepic);
If the latter, does expressjs provide a helper function to determine the request type? My approach so far to determine if req is POST requires underscore:
if (_.size(req.body) == 0)
There is no general rule, the best approach depends on the case you are working on. I think if you want an api endpoint that accept POST and GET requests combined, you should use express function all() like this:
app.all('/api/profilepic', api.get_profilepic);
You should use seperate endpoints for POST and GET when the handler function is not the same.
For more details see:
http://expressjs.com/en/guide/routing.html
Best practice is to separate concerns; therefore, you should have separate functions to handle each HTTP verb. This makes the code easier to maintain.

Resources