aribouius / jsonapi-react

A minimal JSON:API client and React hooks for fetching, updating, and caching remote data.
MIT License
149 stars 28 forks source link

How to use schema with nested objects? #47

Closed laurmurclar closed 2 years ago

laurmurclar commented 2 years ago

Our API returns data with nested attributes eg.

{
    "data": {
        "id": "111",
        "type": "users",
        "attributes": {
            "name": "Some Person",
            "createdAt": "2021-07-15T13:40:51+01:00",
            "updatedAt": "2021-12-13T14:46:23+00:00",
            "options": {
                "startDate": "2021-08-15T00:00:00+01:00",
                "someOtherAttr" : {
                   "deeplyNestedKey": "hello world",
                 }
            }
        }
}

How do you define these nested attributes in the schema? For example, I'd like to have user.options.startDate be coerced to be a Date.

I tried a few things, but none of them coerced the startDate. Top-level dates (eg. user.createdAt) work fine. Some schemas I tried:

const schema = {
  options: {
    type: "options",
    fields: {
      startDate: "date",
    },
  },
  users: {
    type: "users",
    fields: {
      options: {
        type: "options",
      },
    },
  },
};
const schema = {
  users: {
    type: "users",
    fields: {
      options: {
        fields: { startDate: "date" },
      },
    },
  },
};

Does jsonapi-react handle nested objects like this? How do you define them in the schema? I'm happy to make a PR to update the docs and tests if there is a solution

aribouius commented 2 years ago

Hey @laurmurclar, unfortunately this library does not support nested attribute coercion. I think your best bet would be to provide a custom coercion method for the options field.

const schema = {
  users: {
    type: "users",
    fields: {
      options: {
        resolve: options => {
          return {
            ...options,
            startDate: options.startDate ? new Date(options.startDate) : null
          }
        }
      },
    },
  },
};
laurmurclar commented 2 years ago

Thanks @aribouius ! Appreciate the quick response ☺️ In that case, you can close this issue unless you want to track it as a feature request