Use your existed Mongoose schema to generate graphQL types.
Date fields supported, they get serialized to ISO date string
extend
property to pass it, details below.
Full support of all graphQL "Definitions" and "Scalars" besides "GraphQLFloat", because in Mongoose schema you can use only int. numbers. But you can use This package will help you avoid typing schemas for same essence. If you already have Mongoose schema that's enough to generate graphQL type.
How it works.
First:
npm i -S mongoose-schema-to-graphql
or
yarn add mongoose-schema-to-graphql
Make sure that your graphql
package is the same version as used in mongoose-schema-to-graphql
or vice versa.
Then:
;
createType
function accept obj as argument with following structure:
const config = name: 'couponType' //graphQL type's name description: 'Coupon base schema' //graphQL type's description class: 'GraphQLObjectType' //"definitions" class name schema: couponSchema //your Mongoose schema "let couponSchema = mongoose.Schema({...})" exclude: '_id' //fields which you want to exclude from mongoose schema extend: price: type: GraphQLFloat //add custom properties or overwrite existed
After you declared config. object you're ready to go. Examples below:
dbSchemasjs const couponSchema = mongoose;
;; const config = name: 'couponType' description: 'Coupon schema' class: 'GraphQLObjectType' schema: couponSchema exclude: '_id'; config;
It will be equal to:
;; ;
Note: If you pass mongoose type Array
it will be converted to {type: new GraphQLList(GraphQLString)}
If you want to create a list of another type, you would need to declare it in Mongoose schema too:
const quizSchema = mongoose; const customerSchema = mongoose;
Then:
;; const config = name: 'customerType' description: 'Customer schema' class: 'GraphQLObjectType' schema: customerSchema exclude: '_id'; config;
It's equal to:
;; const quizType = name: 'quizType' description: 'quiz type for customer' fields: message: type: GraphQLString updatedAt: type: GraphQLString createdAt: type: GraphQLString ; ;
extend
property in config object.
You can use this field to pass some additional extend. to graphQL type, for example:
;;; const config = name: 'customerType' description: 'Customer schema' class: 'GraphQLObjectType' schema: customerSchema exclude: '_id' extend: price: type: GraphQLFloat ; config;
It's equal to:
;; const quizType = name: 'quizType' description: 'quiz type for customer' fields: message: type: GraphQLString updatedAt: type: GraphQLString createdAt: type: GraphQLString ; ;
If passed extend. already exist in Mongoose schema, for example price: Number
it will be overwrite with prop. we passed in config. object.
If you have any suggestion please leave me a message.