简体   繁体   中英

Client-side vs server-side data manipulation

I just learned how to access express local variables in client-side JS:

https://stackoverflow.com/questions/34618426/express-handlebars-local-variables-in-client-side-js

But this opened a whole new can of worms... Now I don't know what data manipulation to do server side (within the route) and which to do client-side.

For example: Here I am cutting the description property of each database item, so that the first 100 characters can be used as a preview in a featured listing collage.

//routes/index.js
router.get('/', isAuthenticated, function (req, res, next) {
  //Fetching data to populate newest listings collage
  User.find({role: 'organization'}).sort({datecreated: -1}).limit(6).exec(function (err, docs) {
    docs.forEach(function(item){
      item.description = item.description.slice(0,100);
    });
    console.log(docs[0].description);
    res.render('index.hbs', {
      user: req.user, 
      orgsfeatured: docs, 
      message: req.flash('message')
    })
  });
});

Is it more typical/ performant/ maintainable to just send the entire array of objects to the client-side javascript to be sliced?

I know it's a balance between running up the client cpu load vs the server load, but there must be some best practices . Let me know if I am not being clear. Thanks!!

In my experience you can't take a "one-size fits all" approach.

In your posted example, you are limiting your results to 6, and truncating to 100 chars. Doing 6 slices, wouldn't be a huge hit CPU-wise for either side. If the item.description could potentially be thousands of chars each, then do the slice server side, to prevent unneeded data flow. Or, if thousands of users could potentially be calling this code at the same time, and the item.descriptions are close to 100 chars, let the thousands of web browsers do the work.

Not knowing anything about your project, would it be possible to not slice the descriptions at all? You may need the entire description in a popover, or use may use it in some search/filter mechanism. If your design dictates that the strings need truncating, then let CSS do that task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM