zakodium/adonis-mongodb

Spread operator brings unwanted data

maasencioh opened this issue · 6 comments

After #112 a spread operator on .all() returns inner state metadata ($isPersisted, $isLocal, etc) instead of the current data.

const events =  (await eventCursor.all()).map(({ _id, ...rest }) => ({ ... rest, id: _id }));
/*
[
  {
     '$isPersisted': true,
     '$isLocal': false,
     '$isDeleted': false,
     '$collection': Collection { s: [Object] },
     '$originalData': {
       _id: new ObjectId("6127519d992a7f508fe38282"),
       createdAt: 2021-08-26T08:32:29.629Z,
       updatedAt: 2021-08-26T08:32:29.629Z,
       topic: 'b1505',
       data: [Object],
       processors: []
     },
     '$currentData': {
       _id: new ObjectId("6127519d992a7f508fe38282"),
       createdAt: 2021-08-26T08:32:29.629Z,
       updatedAt: 2021-08-26T08:32:29.629Z,
       topic: 'b1505',
       data: [Object],
       processors: []
     },
     '$options': { collection: [Collection], session: undefined }
     id: "6127519d992a7f508fe38282",
   },
]
*/

Models are proxies on the data that currently only intercept get and set operations: https://github.com/zakodium/adonis-mongodb/blob/main/src/Model/proxyHandler.ts

I think we could support spreading with an ownKeys interceptor. Do you expect that {...modelInstance} returns a shallow copy of $currentData ?

Daniel's idea: make {...modelInstance} similar to instance.toJSON()

Related: #72 (comment)

If we implement the public $attributes field, it will be possible to do {...instance.$attributes}

In the mean time, I will make ownKeys throw so that spreading by mistake doesn't do something unexpected

Sorry, I think that the natural behavior for me is to have what's inside $currentData, what could be the difference with the toJSON result?

At the moment, there is no difference (toJSON returns $currentData). But one of the features of Lucid that I want to implement is field serializers. toJSON would call the serializers.