Having the entire schema into the server.js file is not practical, especially if the schema grows bigger, so let’s move the schema into separate folders for easy management:
mkdir ./src/schema/queries -p
mkdir ./src/schema/types -p
mkdir ./src/schema/mutations -p
./src/schema/index.js
const graphql = require('graphql');
const queries = require('./queries');
const mutations = require('./mutations');
var rootQuery = new graphql.GraphQLObjectType({
name: 'Query',
fields: {...queries, ...mutations },
});
module.exports = new graphql.GraphQLSchema({
query: rootQuery
});
./src/schema/types/index.js
let Dogs = require('./dogs.js');
module.exports = {
...Dogs,
};
./src/schema/types/dogs.js
const graphql = require('graphql');
module.exports = new graphql.GraphQLObjectType({
name: 'dogType',
fields: {
id: { type: graphql.GraphQLString },
breed: { type: graphql.GraphQLString },
displayImage: { type: graphql.GraphQLString },
}
});
./src/schema/queries/index.js
let Dogs = require('./dogs.js');
module.exports = {
...Dogs
};
./src/schema/queries/dogs.js
const graphql = require('graphql');
const dogType = require('../types/dogs');
const dogs = require('../../models/mock_data/dogs.js');
module.exports = {
getDogByBreed: {
type: dogType,
args: {
breed: { type: graphql.GraphQLString }
},
resolve: function (_, {breed}) {
var result = dogs.find(function(dog){
return breed == dog.breed;
});
return result;
}
}
}
./src/schema/mutations/index.js
let Dogs = require('./dogs.js');
module.exports = {
...Dogs
};
./src/schema/mutations/dogs.js
const graphql = require('graphql');
const dogs = require('../../models/mock_data/dogs.js');
module.exports = {
addDogBreed: {
type: graphql.GraphQLString,
args: {
id: { type: graphql.GraphQLString },
breed: { type: graphql.GraphQLString },
displayImage: { type: graphql.GraphQLString }
},
resolve: function (_, {id, breed, displayImage}) {
dogs.push({
id: id,
breed: breed,
displayImage: displayImage
});
return "OK!";
}
}
}
./server.js
var express = require('express');
var graphqlHTTP = require('express-graphql');
const schema = require('./src/schema');
// Logger middleware
var logger = function(req, res, next) {
console.log("GOT REQUEST >", req.ip);
next(); // Passing the request to the next handler in the stack.
}
var app = express();
app.use(logger);
app.use('/graphql', graphqlHTTP({
schema: schema,
graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');