Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use schema with nested objects? #47

Closed
laurmurclar opened this issue Dec 13, 2021 · 2 comments
Closed

How to use schema with nested objects? #47

laurmurclar opened this issue Dec 13, 2021 · 2 comments

Comments

@laurmurclar
Copy link

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
Copy link
Owner

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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants