Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const { ApolloServer, gql } = require('apollo-server');
const parseFields = require('graphql-parse-fields');
const typeDefs = gql`
type User {
firstName: String
lastName: String
age: Int
}
type Query {
users: [User]
}
`;
const users = [
{ firstName: 'John', lastName: 'Doe', age: 33 },
{ firstName: 'Jane', lastName: 'Doe', age: 33 }
];
const getUsers = requiredFields => {
return users.map(user => pick(user, requiredFields));
};
const resolvers = {
Query: {
users: (parent, args, context, info) => {
const requiredFields = Object.keys(parseFields(info));
const users = getUsers(requiredFields);
console.log(users);
return users;
}
}
};
const server = new ApolloServer({
typeDefs,
resolvers
});
const pick = (obj, keys) => {
return keys
.map(k => (k in obj ? { [k]: obj[k] } : {}))
.reduce((res, o) => Object.assign(res, o), {});
};
server.listen(7000).then(({ url }) => {
console.log(`Server running at ${url}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment