Skip to content

Instantly share code, notes, and snippets.

@arleyhr
Last active September 9, 2021 00:04
Show Gist options
  • Save arleyhr/68124e874dfda697859b442e80bd6906 to your computer and use it in GitHub Desktop.
Save arleyhr/68124e874dfda697859b442e80bd6906 to your computer and use it in GitHub Desktop.
GraphQL modularize
const typeDefinitions = `
type User {
id: ID!
author: User!
summary: String!
content: String!
image: String!
tags: [Tag!]!
}
type Tag {
id: ID!
name: String!
posts: [Post]
}
input postData {
author: User!
summary: String!
content: String!
image: String!
tags: [Tag!]!
}
`
const queries = `
posts: [Post]
tags: [Tag]
postsByTag(tagId: Int!): [Post]
`
const mutations = `
postAdd(user: postData ): Post
postDelete(id: Int!): Post
`
const resolvers = {
Query: {
posts: (root, args) => { ... } // resolve
postsByTag: (root, args) => { ... } //resolve
},
Mutation: {
postAdd: (root, args) => { ... } // resolve
postDelete: (root, args) => { ... } // resolve
}
}
module.exports = {
typeDefinitions,
queries,
resolvers,
mutations
}
import { makeExecutableSchema } from 'graphql-tools'
import glob from 'glob'
import path from 'path'
let typeDefs = []
let allQueries = []
let allResolvers = { Query: {}, Mutation: {} }
let allMutations = []
// Search for files with the name 'schema'
const schemas = glob.sync(`${__dirname}/../../api/**/*schema.js`)
schemas.forEach(file => {
// Require each file
let { typeDefinitions, queries, resolvers, mutations } = require(path.resolve(file))
typeDefs.push(typeDefinitions)
allMutations.push(mutations || '')
allQueries.push(queries)
Object.keys(resolvers).forEach(key => {
if(!allResolvers[key])
allResolvers[key] = {}
Object.assign(allResolvers[key], resolvers[key])
})
})
const mergedSchema = `
${typeDefs.join('\r')}
type Query {
${allQueries.join('\r')}
}
type Mutation {
${allMutations.join('\r')}
}
`
const schema = makeExecutableSchema({
typeDefs: mergedSchema,
resolvers: allResolvers
})
export default schema
const typeDefinitions = `
type User {
id: ID!
email: String!
name: String!
picture: String
}
input userData {
name: String!
email: String!
picture: String!
}
`
const queries = `
users: [User]
`
const mutations = `
userAdd(user: userData ): User
userUpdate(id: Int!, user: userData): User
`
const resolvers = {
Query: {
users: (root, args) => { ... } // resolve
},
Mutation: {
userAdd: (root, args) => { ... } // resolve
userUpdate: (root, args) => { ... } // resolve
}
}
module.exports = {
typeDefinitions,
queries,
resolvers,
mutations
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment