adding field returning GraphQLListType on user object
idkjs opened this issue · 4 comments
Thinking out loud here...Im trying to get my head around this.
So if I have a user and then i want that user to be able to return a list of of data, what would that look like.
If this is my standard schema generally...how would I convert that to a contextible format.
Lets assume I have set up place.js by copying user.js, how would i call the places query from user?
Something like this in root.js?
async getUsers (args) {
let {User} = this.$context;
let data = (await User.findAll(args)) => Place.find({});
return data.map((d) => new User(d));
//something else here..
},
standard graphql sudo...
type Query {
user(_id: String!): User
place(_id: String): Place
places: [Place]
},
type User {
_id: String!
name: String!
places: [Place]
},
type Place {
_id: String!
name: String!
address: String!
city: String!
votes: Int!
}
Thanks.
@idkjs graphql-example should help.
@idkjs This is a full example for your schema:
var {graphql, buildSchema} = require('graphql');
var {Context, Schema} = require('contextable');
/* Contextable */
var placeSchema = new Schema({
fields: {
userId: {type: 'Integer'},
name: {type: 'String'}
}
});
var userSchema = new Schema({
fields: {
id: {type: 'Integer'},
name: {type: 'String'}
},
instanceMethods: {
places () {
return this.$context.fakeDB.places.filter((data) => (
data.userId === this.id
)).map((data) => (
new this.$context.Place(data)
));
}
}
});
var rootSchema = new Schema({
instanceMethods: {
users () {
return this.$context.fakeDB.users.map((data) => (
new this.$context.User(data)
));
}
}
});
var ctx = new Context({
fakeDB: {
users: [
{id: 1, name: 'John'},
{id: 2, name: 'Bob'},
],
places: [
{userId: 1, name: 'New York'},
{userId: 2, name: 'San Francisco'}
]
}
});
ctx.defineModel('Place', placeSchema);
ctx.defineModel('User', userSchema);
ctx.defineModel('Root', rootSchema);
/* GraphQL */
var schema = buildSchema(`
type Query {
users: [User]
}
type User {
name: String!
places: [Place]
}
type Place {
name: String!
}
`);
var root = new ctx.Root();
graphql(schema, `{
users {
name
places {
name
}
}
}`, root).then((response) => {
console.log(JSON.stringify(response, null, 2));
});
The new API will be even simpler (ref. #7).
Thanks for that. I just reread some of the readme. The new language is what I am trying to get my head around. So an instance is an instantiated class and/or an extended class with its own methods. I'll take another looks to figure out what virtual fields compare to as a concept. You might consider a tl;dr at the top of your monolithic explanation. Lead with the facts!
Thanks for sharing the project.
I agree, the docs should be shorter. The new API with better docs will be available in ~January.