0

I need to run a patch (or an update) in Objection.js, based on a condition. I have this code:

if (leavenMachine.ping == true){
   MachinesInit.query()
                .patch({status: 'OK', online:"yes"})
                .where('machine', 'leaven machine')
                .where('type', 'M');
}else {
  MachinesInit.query()
                .patch({status: 'OK'})
                .where('machine', 'leaven machine')
                .where('type', 'M');
}

I need to refactor it so that I don't need two queries (one inside the if condition and the second inside the else), but just one, embedding the condition inside the patch method. Is it possible? How can I do?

Dav
  • 33
  • 5

1 Answers1

1

You can extract the patch object to a variable:

const patchData = (leavenMachine.ping == true) ? {status: 'OK', online:"yes"} : {status: 'OK'}

Afterwards, just call the query:

MachinesInit.query()
            .patch(patchData)
            .where('machine', 'leaven machine')
            .where('type', 'M');

You could pass the value of patchData directly to the patch call, but this way it's more readable.

Hope this helps.

Romi Halasz
  • 1,949
  • 1
  • 13
  • 23
  • It's exactly what I wanted. I didn't know I can use a variable as an argument of patch method. Thank you! – Dav Jan 29 '20 at 09:22
  • I see. In your example the patch method takes as parameter an anonymous object. If you store that same object in a variable and pass that variable to patch, it's the same thing. Glad I could help! – Romi Halasz Jan 29 '20 at 09:37