GraphQL List
Let assume we have the next GraphQL Type object:
import {categoryType} from './category';
let selectType = new GraphQLObjectType({
name: 'selectType',
fields: {
value: {type: GraphQLString},
label: {type: GraphQLString}
}
});
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},
categories: {type: new GraphQLList(categoryType)},
recommended: {type: new GraphQLList(selectType)},
address: {
type: new GraphQLObjectType({
name: 'addressType',
fields: () => ({
shipToAddress1: {type: GraphQLString},
shipToAddress2: {type: GraphQLString},
billToAddress1: {type: GraphQLString},
billToAddress2: {type: GraphQLString}
})
})
}
}
});
In example above selectType
was created just to give shape for the list. We don't have any separate collection in data-base for selectType
and as a result this type doesn't have Query or Mutation methods.
categoryType
is a separate essence with its separate collection in the data-base and its own Query and Mutation methods.
So this means that we will see categoryType
on the side menu of CMS and we can manage data in that collection.
Difference in UI of CMS between this two cases will be that in the first case with selectType
, CMS will use data it gets from productType
to set selected options in select menu, as seen on screenshot below:
You don't have any other options. If you want to add new options you have to use the button [+] which will trigger popup window where you can create new option:
In case with categoryType
you don't have the button [+] and if you want to add a new option you have to do it from the side menu.
By default CMS will set as selected options data from current productType
and automatically will pre-populate options with categoryType
items from data-base.
To create or update Type with GraphQLList you have to use the same approach as we used with nested fields.
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},,
categories: {type: GraphQLString},
recommended: {type: GraphQLString}
address: {type: GraphQLString}
},
resolve: (_, args) => productResolvers.create(args)
},
...
})
});
Resolver example:
productResolvers.create = (args) => {
args.categories = JSON.parse(args.categories);
args.recommended = JSON.parse(args.recommended);
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);
});
});
};