Magento2 Integration – GraphQL and ReactJS Data Retrieval Issues

apijavascriptmagento2magento2.2.2product

What I'm trying to do is modify frontend in magento2 using reactjs to make it more faster to implements and faster response with actions on the website. But first thing I must to do is retreving data from magento2 api using graphql, then make it render in reactjs, cuz the frontend will be connecting to backend by graphql. The problem is, magento2 api have 1 object that has fields with the same key name but diffrent types, this is the custom_attributes– the key name value has 1 field with list of string and the rest is just string. I have already tried to use union and interface while building schema for api in graphql, but it always give me an error that my schema cannot provide interfaces, nor unions. Maybe someone was using magento2 api with graphql and give me some advice?
Btw. I heared about schema.org that can integrate with reactjs and graphql as well but I didnt saw good enough tutorials that shows how to connect them all.

To be precise, fragment from api looks like that:

{
 custom_attributes: [
  {
   attribute_code: some string
   value: some string
  }
  {
   attribute_code: some string
   value: [
    some string,
    some string,
    some string
   ]
  }
 ]
}

Best Answer

Solution.

const {makeExecutableSchema} = require('graphql-tools');

const links = [
    {
        "custom_attributes": [
            {
                "attribute_code": "description",
                "value": "<p>Some description here</p>"
            },
            {
                "attribute_code": "category_id",
                "value": [
                    "2",
                    "3",
                ]
            }

        ]
    }
];

const typeDefs = `

  type Link {
    custom_attributes: [Custom]
  }

  union Custom = One | Two

  type One {
    attribute_code: String
    value: String
  }

  type Two {
    attribute_code: String
    value: [String]

  }

  type Query {
    allLinks: [Link]!

  }

`;



const resolvers = {
    Query: {
        //set data to Query
        allLinks: () => links,
    },
    Custom: {
        __resolveType(Object, context, info) {
            //console.log(Object, context, info);
            if (typeof Object.value=== 'string') {
                return 'One'
            }

            if (Array.isArray(Object.value)) {
                return 'Two'
            }
            return null;
        }
    },
};

// Generate the schema object from your types definition.
module.exports = makeExecutableSchema({
    typeDefs,
    resolvers
});

Execute query

{
    allLinks {
        custom_attributes {
            ... on One {
                description
                value
            }
            ... on Two {
                description
                aliasval : value
            }

        }
    }
}
Related Topic