beforeSave and afterSave request source check to perform it or not

Hi, It’s possible to know from what kind of function has the beforeSave or afterSave been called?

For example I need to perform some actions if beforeSave is called by a contract event Sync the first time, but not if I’m updating some values of the collections with a cron job.

It’s happening now that I’m writing new data on the collection when an event is synced, then I need with a cron to update the collection rows once there is a record on another collection. But I want only to write 2 fields, with the beforeSave also all the others are written causing inconsistency.

Thank you

You could check if it is updating first time or not by using a flag. Id the flag is already present then it was already updated.

You mean with a collection field?

With a field that you could add in a new column.

Considering that the first time the collection is populated is from a contract event sync, I should pass the field from the contract first time?

No, you can pass it directly in beforeSave or set it in afterSave

If I got it correctly in the flow:

in the before save I make as a first step query in the DB to check if the same row has been already added

if not => execute the beforeSave as expected and at the end set the flag at true

Next time the same check will get the true and will avoid to be executed, is this the flow?

I think that you can check directly in beforeSave current object without to do a db query, it may be already present in the request parameter, and you can check if that flag is set to true or not already

you set that flag directly in beforeSave, not at the end

ok so the request already has the data from the collection, and I can retrieve it from it.

I’m asking because the collection the first time is created with the event, and does not contain the column, I would create it directly in the beforeSave

Thank you

EDIT I suspect is a permission issue, I open a new thread

I’m trying with an initial check

if (!request.object.get(“checkAlreadyDone”)) {
… logic here
}

but now anything is executed, the row obviously still not exist (is the first save from the contract sync event).

I’m receiving this error
2022-05-31T13:56:21.244Z - Error: Permission denied for action update on class ClassName.
at Function.validatePermission (/moralis-server/lib/Controllers/SchemaController.js:1512:11)
at SchemaController.validatePermission (/moralis-server/lib/Controllers/SchemaController.js:1517:29)
at /moralis-server/lib/Controllers/DatabaseController.js:542:63
at processTicksAndRejections (node:internal/process/task_queues:96:5)

I’ve also tried with a check with false / undefined.

So if the row doesn’t exist, how could be performed the check?

Thank you