zakodium / adonis-mongodb

MongoDB provider for AdonisJS 5
https://zakodium.github.io/adonis-mongodb/
Other
64 stars 12 forks source link

Spread operator brings unwanted data #114

Open maasencioh opened 3 years ago

maasencioh commented 3 years ago

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",
   },
]
*/
targos commented 3 years ago

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 ?

targos commented 3 years ago

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

targos commented 3 years ago

Related: https://github.com/zakodium/adonis-mongodb/issues/72#issuecomment-876122196

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

targos commented 3 years ago

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

maasencioh commented 3 years ago

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?

targos commented 3 years ago

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.