sequelize-graphql-tools
v2.0.2
Published
Utils to generate graphql schema, types, querys and mutations from sequelize models
Downloads
5
Readme
sequelize-graphql-tools
Utils to generate graphql schema, types, querys and mutations from sequelize models
Installation
npm i sequelize-graphql-tools graphql graphql-compose graphql-fields graphql-iso-date sequelize
Use
One model to GraphqlType
const { modelToType } = require('sequelize-graphql-tools')
const db = require('./models') // Sequelize instance with all models imported
const options = {
ignore: ['password'] // Hide password in fields
}
const UserTC = modelToType(db.User.name, db.User.rawAttributes, options)
All model to GraphqlType
const { createTypes } = require('sequelize-graphql-tools')
const db = require('./models') // Sequelize instance with all models imported
const options = {
ignore: ['Session'], // Ignore models
fields: {
User: { ignore: ['password'] } // Hide password in User fields
}
}
const allTypes = createTypes(db, options)
const UserTC = allTypes.User
Append associations
const { createTypes, appendAssociations } = require('sequelize-graphql-tools')
const db = require('./models') // Sequelize instance with all models imported
const options = {
ignore: ['Session'], // Ignore models
fields: {
User: { ignore: ['password'] } // Hide password in User fields
}
}
const allTypes = createTypes(db, options)
Object.keys(allTypes).forEach(name => {
appendAssociations(allTypes, name, db[name].associations)
})
Generate all querys and mutations
const { GraphQLSchema, GraphQLObjectType } = require('graphql/type')
const { createTypes, appendAssociations } = require('sequelize-graphql-tools')
const db = require('./models') // Sequelize instance with all models imported
const options = {
ignore: ['Session'], // Ignore models
fields: {
User: { ignore: ['password'] } // Hide password in User fields
}
}
const allTypes = createTypes(db, options)
Object.keys(allTypes).forEach(name => {
appendAssociations(allTypes, name, db[name].associations)
})
const querys = Object.keys(allTypes).reduce((acc, name) => {
return { ...acc, ...createQuery(db[name], allTypes[name].gqType) }
}, {})
const mutations = Object.keys(allTypes).reduce((acc, name) => {
return {
...acc,
...createMutation(db[name], allTypes[name].gqType)
}
}, {})
const query = new GraphQLObjectType({
name: 'query',
fields: () => ({ ...querys })
})
const mutation = new GraphQLObjectType({
name: 'mutation',
fields: () => ({ ...mutations })
})
const schema = new GraphQLSchema({ query, mutation })