Skip to content

Instantly share code, notes, and snippets.

@bradley-curran
Created February 18, 2022 00:16
Show Gist options
  • Save bradley-curran/5eff50d39bde41ef8de6cef665ad77c3 to your computer and use it in GitHub Desktop.
Save bradley-curran/5eff50d39bde41ef8de6cef665ad77c3 to your computer and use it in GitHub Desktop.
makeExecutableSchema without graphql-tools
const { buildSchema } = require('graphql');
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const makeExecutableSchema = (schema, resolverMap) => {
const executableSchema = buildSchema(schema);
Object.keys(resolverMap).forEach(typeKey => {
const fields = executableSchema.getType(typeKey).getFields();
Object.keys(resolverMap[typeKey]).forEach(fieldKey => {
fields[fieldKey].resolve = resolverMap[typeKey][fieldKey];
});
});
return executableSchema;
};
// example usage
const schema = `
type Query {
allTodoLists: [TodoList]
}
type TodoItem {
text: String
done: Boolean
}
type TodoList {
title: String
totalCount: Int
notDoneCount: Int
items: [TodoItem]
}
`;
const todoLists = [
{
title: '5 year plan',
items: [
{ text: 'Get Married', done: false },
{ text: 'Have Babies', done: false },
],
},
{
title: 'Grocery List',
items: [
{ text: 'Potatoes', done: false },
{ text: 'Rum', done: true },
],
},
];
const resolvers = {
Query: {
allTodoLists: () => todoLists,
},
TodoList: {
totalCount: source => {
return source.items.length;
},
notDoneCount: source => {
return source.items.filter(item => !item.done).length;
},
},
};
makeExecutableSchema(schema, resolvers);
const app = express();
app.use(
'/graphql',
graphqlHTTP({
schema: makeExecutableSchema(schema, resolvers),
graphiql: true,
})
);
app.listen(4000);
// example query
{
allTodoLists {
title
totalCount
notDoneCount
items {
text
done
}
}
}
// example response
{
"data": {
"allTodoLists": [
{
"title": "5 year plan",
"totalCount": 2,
"notDoneCount": 2,
"items": [
{
"text": "Get Married",
"done": false
},
{
"text": "Have Babies",
"done": false
}
]
},
{
"title": "Grocery List",
"totalCount": 2,
"notDoneCount": 1,
"items": [
{
"text": "Potatoes",
"done": false
},
{
"text": "Rum",
"done": true
}
]
}
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment