Nested Fields

GraphQL CMS also supports Types with nested fields.

Let assume we have the following GraphQL Type object:

export let productType = new GraphQLObjectType({
    name: 'productType',
    description: 'Product model',
    fields: {
        _id: {type: GraphQLString},
        price: {type: GraphQLString},
        name: {type: GraphQLString},
        createdAt: {type: GraphQLString},
        updatedAt: {type: GraphQLString},
        isPublished: {type: GraphQLBoolean},
        address: {
            type: new GraphQLObjectType({
                name: 'addressType',
                fields: () => ({
                    shipToAddress1: {type: GraphQLString},
                    shipToAddress2: {type: GraphQLString},
                    billToAddress1: {type: GraphQLString},
                    billToAddress2: {type: GraphQLString}
                })
            })
        }
    }
});

In CMS it will look like the following:

To create or update an item with nested fields in the data-base, all you need to do is specify the Mutation method property with nested fields as 'String' type, so CMS will pass JSON to your resolver, where you can parse JSON to update or create new item.

Mutation method example:

const mutations = new GraphQLObjectType({
    name: 'Mutation',
    fields: () => ({
    ...
    productType_create: {
            type: productType,
            description: 'add new product',
            args: {
                _id: {type: GraphQLString},
                price: {type: GraphQLString},
                name: {type: GraphQLString},
                createdAt: {type: GraphQLString},
                updatedAt: {type: GraphQLString},
                isPublished: {type: GraphQLBoolean},
                address: {type: GraphQLString}
            },
            resolve: (_, args) => productResolvers.create(args)
        },
        ...
     })
});

Resolver example:

productResolvers.create = (args) => {
    args.address = JSON.parse(args.address);
    let newProduct = new Product(args);

    return new Promise((resolve, reject) => {
        newProduct.save((err, res) => {
            err ? reject(err) : resolve(res);
        });
    });
};

results matching ""

    No results matching ""