How can we access the dynamically added component fields (i.e., JSON fields) using Strapi CMS?

How can we access the dynamically added component fields (i.e., JSON fields) using Strapi CMS?


0

Context:

I have a custom component ( autocomplete with list of options from external api ) that allows me to select an option based on an API request. After the selection, the body of the option becomes part of the structure and looks like this (where ‘type’ is a field of the custom component):

Grapql response:

{
  "data": {
    "newsCollection": {
      "data": [
        {
          "id": "23",
          "attributes": {
            "type": [
              {
                "id": "DSDSD",
                "name": "DSADASDASD",
                "name2": "DSADASDASD",
              },
              {
                "id": "DSDSD3",
                "name": "DSADASDASD",
                "name2": "DSADASDASD",
              }
            ]
          }
        }
      ]
    }
  }
}

When I try to make a GraphQL request to selectively get the fields of this component, or to filter by nested fields ( name, name2, id ), I run into a problem that GraphQL doesn’t know these fields exist because it identifies the component as JSON.

Example:

query Test(
    $filters: NewsFiltersInput
    $pagination: PaginationArg = {}
    $sort: [String] = []
    $publicationState: PublicationState = LIVE
){
 newsCollection(
      filters: $filters
      pagination: $pagination
      sort: $sort
      publicationState: $publicationState
    ) {
  data {
    id
    attributes {
     type {
       ..... I can't identify fields here 😞
     }
    }
  }
}
}

Is there a way to solve this problem in Strapi? :pray:

I tried to override schema such way in ./src/index.js file

module.exports = {
  /**
   * An asynchronous register function that runs before
   * your application is initialized.
   *
   * This gives you an opportunity to extend code.
   */
  register({ strapi }) {
    const extensionService = strapi.plugin("graphql").service("extension");

    const extension = () => ({
      typeDefs: `
        type Type {
           name: String!
         }

          type ObetaTeaser {
            type: [Type]!
          }
      `,
    });
    extensionService.use(extension);
  },

  bootstrap(/*{ strapi }*/) {},
};

but we cann’t override, but only extend existing type with new fields(

It would be great if strapi has ability to define custom type for custom fields but not JSON or string only

Share
Improve this question

1

  • You can’t search by json fields in strapi

    – antokhio

    Aug 5 at 23:01

1 Answer
1

Reset to default


0

The problem is solved using a custom resolver that creates a duplicate of the field and describes its type.

Share
Improve this answer



Leave a Reply

Your email address will not be published. Required fields are marked *