Loopback: Atomic read and update
Asked Answered
H

1

2

is there a way to implement something like this in loopback?

LOCK
 READ
 INCREMENT
UNLOCK

I would like to keep counters as database values, each key is a counter (or a setting), and they shouldn't accessed my multiple requests at the same time.

Also this should work for local requests too (no remoteHooks)

Thanks

Hickey answered 18/10, 2016 at 12:19 Comment(0)
M
1

If you are using the mongoDB connector, this is supported by extended operators.

MyModel.updateAll(
  { id: 123' },
  { '$inc': { myproperty: 1 }}, // increment myproperty by 1
  { allowExtendedOperators: true }
);

Otherwise, you can use transactions as a workaround for some connectors.

Mintz answered 19/10, 2016 at 13:32 Comment(4)
Nope, does not work properly. The value is updated, but I cannot read the contents anywhere. Sure, I can fire up another request, but being async I cannot be sure if other requests have been sent in the meanwhile.Hickey
What do you mean you cannot read the contents anywhere ? And are you using extended operators or transactions ?Mintz
I'm using operators (mongo database), as soon as I tell the model to update all matching records it returns a count of updated records, but I don't know yet the value. I can read it afterwards, but again the atomicity is broken, because another operation might have been launched in the meanwhile.Hickey
ah yes that's a feature missing from the update. Sadly the MongoDB connector does not support this at the moment. Unless you're willing to switch DB, I don't see any solution here unless implementing yourself transactions in the loopback mongodb connector.Mintz

© 2022 - 2024 — McMap. All rights reserved.