Skip to content

Instantly share code, notes, and snippets.

@icebob
Created July 29, 2016 08:19
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save icebob/553c1f9f1a9478d828bcb7a08d06790a to your computer and use it in GitHub Desktop.
Save icebob/553c1f9f1a9478d828bcb7a08d06790a to your computer and use it in GitHub Desktop.
Merge GraphQL schemas & resolvers in modules
let moduleQueries = [];
let moduleTypeDefinitions = [];
let moduleMutations = [];
let moduleResolvers = [];
let files = config.getGlobbedFiles(path.join(__dirname, "**", "*schema.js"));
// Load schema files
files.forEach((file) => {
let moduleSchema = require(path.resolve(file));
moduleQueries.push(moduleSchema.schema.query);
moduleTypeDefinitions.push(moduleSchema.schema.typeDefinitions);
moduleMutations.push(moduleSchema.schema.mutation);
moduleResolvers.push(moduleSchema.resolvers);
});
// --- MERGE TYPE DEFINITONS
const schema = `
type Query {
${moduleQueries.join("\n")}
}
${moduleTypeDefinitions.join("\n")}
type Mutation {
${moduleMutations.join("\n")}
}
schema {
query: Query
mutation: Mutation
}
`;
// --- MERGE RESOLVERS
function mergeModuleResolvers(baseResolvers) {
moduleResolvers.forEach((module) => {
baseResolvers = _.merge(baseResolvers, module);
});
return baseResolvers;
}
module.exports = {
schema: [schema],
resolvers: mergeModuleResolvers({})
};
const query = `
devices(limit: Int, offset: Int, sort: String): [Device]
device(id: Int, code: String): Device
`;
const typeDefinitions = `
type Device {
id: Int!
code: String!
address: String
type: String
name: String
description: String
status: Int
lastCommunication: Timestamp
}
`;
const mutation = ``;
const resolvers = {
Query: {
devices(root, args, context) {
return applyLimitOffsetSort(Device.find({}), args).exec();
},
...
},
Mutation: {
}
};
module.exports = {
schema: {
query,
typeDefinitions,
mutation
},
resolvers
};
const query = `
posts(limit: Int, offset: Int, sort: String): [Post]
post(id: Int, code: String): Post
`;
const typeDefinitions = `
type Post {
id: Int!
code: String!
title: String
content: String
author: User!
views: Int
voters(limit: Int, offset: Int, sort: String): [User]
upVoters(limit: Int, offset: Int, sort: String): [User]
downVoters(limit: Int, offset: Int, sort: String): [User]
votes: Int,
createdAt: Timestamp
updatedAt: Timestamp
}
`;
const mutation = `
upVote(postID: Int!): Post
downVote(postID: Int!): Post
`;
const resolvers = {
Query: {
posts(root, args, context) {
return applyLimitOffsetSort(Post.find({}), args).exec();
},
...
},
Mutation: {
upVote(root, args, context) {
...
},
downVote(root, args, context) {
...
}
}
};
module.exports = {
schema: {
query,
typeDefinitions,
mutation
},
resolvers
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment