nicklandgrebe / active-resource.js

ActiveResource.js - API resource relational mapping in JavaScript
https://active-resource.js.org
MIT License
133 stars 20 forks source link

Support for JSONB, other nested data structures #45

Open CharlieIGG opened 5 years ago

CharlieIGG commented 5 years ago

My backend server is using PostgreSQL as a DB. For a specific field in my model, I have a JSONB column.

When I call:

myResourceInstance.update({ 
  jsonField: {stuff: 1234}
})

Then the update reaches my server without this parameter (basically it updates the model instance without any actual changes).

If I instead send some other primitive data type as the value of jsonField then I can see it come through in the request's parameters.

Any ideas how to make this work, without moving away from the JSON:API standard in my server?

nicklandgrebe commented 5 years ago

I made some specs to reproduce but they passed. Can you post the resource class definition?

CharlieIGG commented 5 years ago

This is the real thing:

import resourceLibrary from './library'

class Car extends resourceLibrary.Base {
    static define() {
        this.attributes('year', 'prices')
        this.belongsTo('engine')
        this.belongsTo('make')
        this.belongsTo('model')
    }
}

export default resourceLibrary.createResource(Car);

As a temporary workaround for this I've decided to call

myResourceInstance.update({ 
  jsonField: JSON.stringify({stuff: 1234})
})

And setup a before_save filter on my Rails app that parses that JSON before attempting to save it.

nicklandgrebe commented 5 years ago

update only sends changed fields to the server. If an attribute is not added in attributes then it won't be sent:

this.attributes('year', 'prices', 'jsonField')

CharlieIGG commented 5 years ago

@nicklandgrebe my example didn't match the real-world definition of the resource itself. My bad.

In the real example prices is the JSONB field. And as you can see it was already declared.

nicklandgrebe commented 5 years ago

If instead of using update you use assignAttributes, what does changedFields return?

CharlieIGG commented 5 years ago

@nicklandgrebe I'll test it out either today or tomorrow and get back to you. 👍

CharlieIGG commented 5 years ago

Finally had a chance to test this out.

if I call:

car.assignAttributes({
        prices: update,
})

I get: image