vadimdemedes / mongorito

🍹 MongoDB ODM for Node.js apps based on Redux
1.38k stars 90 forks source link

toJS method #204

Open cherealnice opened 6 years ago

cherealnice commented 6 years ago

Hi,

Thanks for making mongorito!

I am currently integrating with graphql and the only way I can send it data in JS form (unless I'm missing something) is by stringifying to JSON, and then parsing it back. Is there a better way? If not, I'm more than happy to make a PR if you can point me in the right direction.

Thanks!

wesleycoder commented 6 years ago

I'm using GraphQL too. I'm not sure what do you mean by serializing and parsing it.

I think you do not need to stringify any data to JSON, you only need to call instance.get() on each instance of model before passing to the Schema, this should give you a raw object containing the data from the instance.

As far as I know you can pass any raw JavaScript object to the GraphQL Schema and it will serialize them for you.

If you mean to have another way of passing the data to the client other than JSON I'm sure you cannot do it with GraphQL as its nature is to be a JSON API.

wesleycoder commented 6 years ago

Following this, i found that actually a toJSON method is implemented in the Model class. But testing this doesn't work with graphql. It seems to be because of how GraphQL serializes the objects passed to it. It seems that graphql doesn't use JSON.stringify in order to call toJSON on Model instances, it may be implementing his own serializer.

cherealnice commented 6 years ago

Thanks for the responses. Looks like I tried to call get() on the collection, which didn't work, but when I map over and call get() it works.

wesleycoder commented 6 years ago

I'm glad I could help. That's also what I'm doing (.map and call .get()).

However, I'm still curious on how could we make graphql aware of the method .toJSON on the instances and serialize with them.