0
votes

So, I want to have a function, that would reorder my records with orderId

I am passing an array like this:

[
  {id: "5b1007aeb39c961a40540db9", orderId: 0},
  {id: "5b150352184eb8471c34cf7c", orderId: 1}
]

and what I want is to multiple update all records with that ids with the orderId

so how can I do that?

I am trying something like this.... but it's not working, I imagine it is not chaining the promises at all ...

'use strict';

module.exports = function(Matchtimelineevents) {
  Matchtimelineevents.reorder = function(items, cb) {
    let count = 0;

    if (typeof items !== 'undefined' && items.constructor === Array) {
      items.forEach(item => {
        Matchtimelineevents.update({'id': item.id, 'orderId': item.orderId}, function() {
          count++;
          console.log('UPDATING: ' + item.id, item.orderId, count);
        });
      });
      // Matchtimelineevents.bulkUpdate(items, null, function() {
      //   console.log(items);
      // });
    }

    cb(null, count);
  };

  Matchtimelineevents.remoteMethod('reorder', {
    accepts: {
      arg: 'items',
      type: 'array',
    },
    returns: {
      arg: 'count',
      type: 'number',
    },
    http: {'verb': 'patch', 'path': '/reorder'},
    description: 'Reorder the items by orderId',
  });
};

What is the best way to do that?

1

1 Answers

0
votes

Try to use updateAll with where like this:

const updateAllToPromise = item => new Promise((resolve, reject) => {
  Matchtimelineevents.updateAll({
    where: { id: item.id },
  }, {
    orderId: item.orderId,
  }, function (err) {
    if (err) resolve(false);
    else resolve(true);
  });
});

Matchtimelineevents.reorder = (items, cb) => {
  if (!Array.isArray(items)) cb(new Error('Items not is a Array object'));
  else {
    Promise.all(items.map(item => updateAllToPromise(item)))
      .then(items => cb(null, items.filter(item => item).length))
      .catch(cb)
  }
};