const CompanyType = new GraphQLObjectType({
name: 'Company',
fields: {
id: {type: GraphQLString},
name: {type: GraphQLString},
description: {type: GraphQLString}
}
});
const UserType = new GraphQLObjectType({
name: 'User', // name
fields: { // properties
id: {type: GraphQLString},
firstName: {type: GraphQLString},
age: {type: GraphQLInt},
company:{type: CompanyType}
}
});
One user --> one company one company --> many user
company:{type: CompanyType}
resolve 的作用就是,companyId和company关联
const CompanyType = new GraphQLObjectType({
name: 'Company',
fields: {
id: {type: GraphQLString},
name: {type: GraphQLString},
description: {type: GraphQLString}
}
});
const UserType = new GraphQLObjectType({
name: 'User', // name
fields: { // properties
id: {type: GraphQLString},
firstName: {type: GraphQLString},
age: {type: GraphQLInt},
company: {type: CompanyType, resolve(parentValue, args){
return axios.get(`http://localhost:3000/companies/${parentValue.companyId}`)
.then(res => res.data)
}}
}
});
{
user(id: "23"){
firstName,
age,
company{
id,
name,
description
}
}
}
user 通过root query找出user, user通过resolve找到company,
const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields: {
user: {
type: UserType,
args: {id: {type: GraphQLString}},
resolve(parentValue, args) {
return axios.get(`http://localhost:3000/users/${args.id}`)
.then(resp => resp.data)
}
},
company: {
type: CompanyType,
args: {id: {type: GraphQLString}},
resolve(parentValue, args){
return axios.get(`http://localhost:3000/companies/${args.id}`)
.then(resp => resp.data)
}
}
}
});
Fragement,可以复用的
query findCompany {
company(id: "1"){
id,
name
}
}
query findCompany {
apple:company(id: "1"){
id,
name
}
google:company(id: "1"){
id,
name
}
}
query fragment可以复用
const mutation = new GraphQLObjectType({
name: "Mutation",
fields: {
addUser: {
type: UserType, // not aways to return
args: {
firstName: {type:GraphQLString},
age: {type: GraphQLInt},
companyId: {type:GraphQLString}
},
resolve(parentValue, args){
}
}
}
});