Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

mooseql

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mooseql

Build GraphQL Schema based on Mongoose model

  • 0.1.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
16
increased by60%
Maintainers
1
Weekly downloads
 
Created
Source

Version js-standard-style npm download Build Status Coverage Status


Both Graphql and Mongoose are aim for improving and simplifing the developing workflow, but it is verbose to use them together, you have to build repeated Graphql type based on Mongoose schema, create simple CRUD method for each model. MooseQL is created to glue Mongoose to Graphql for making everything to become easy again.

Installation

npm install mongoose --save

Getting Started

1. Creating Mongoose model as usual
import mongoose, { Schema } from 'mongoose'
const userSchema = new Schema({
  name: {
    first: { type: String, required: 'first name required' },
    last: String
  },
  school: { type: Schema.Types.ObjectId, ref: 'School' }
})
export const UserModel = mongoose.model('User', userSchema)
2. Passing model to MooseQL to get GraphQL schema
import mooseql from 'mooseql'
const mySchema = mooseql([UserModel])
3. That's it, you can use it now, let's using express + express-graphql for example

Server side

import express from 'express'
import graphqlHTTP from 'express-graphql'

const app = express()
app.use('/graphql', graphqlHTTP({
	schema: mySchema
}))
app.listen(3000)

Client side

- Create a new user

post('/graphql')
 .send({
   query: `mutation create {
     user: createUser(
       name_first: "wwayne"
       school: school.id
     ) {
      id,
      name { 
        first,
        last
      },
      school {
        id,
        schoolName
      }
     }
   }`
 })

Query

See we have a Mongoose schema for User model:
{
  name: {
    first: String,
    last: {
      fst: String,
      snd: Number
    }
  },
  userName: { type: String, required: [true, 'userName is required'] },
  age: Number,
  isBot: Boolean,
  birth: { type: Date, default: Date.now },
  binary: Buffer,
  info: Schema.Types.Mixed,
  hobbies: { type: [String], required: 'hobbies should have one at least' },
  currentSchool: { type: Schema.Types.ObjectId, ref: 'School' },
  education: [{ type: Schema.Types.ObjectId, ref: 'School' }]
}
You can query like this after using mooseql to generate the schema
`user (
  	id: "${userInstance.id}"
	name_first: "wayne",
	userNames: ["wwayne01", "wwayne02"],
	age: 1,
	isBot: false,
	birth: "${new Date(2016, 8, 15)}",
	binary: "${new Buffer('wayne')}",
	hobbies: ["basketball"],
	currentSchool: "${schoolInstance.id}"
	education: ["${schoolInstance.id}"]
 ) {
   id
   name {
    first
   }
   currentSchool {
     id
     name
   }
   education {
   	 id
   }
 }`
Key points:
  • Query by id or ids is available for every model
  • You can query by plural of the attribute, e.g. name -> names
  • If the attribute is plural, you can't query by its singular
  • When you want to use an object as query arguments, use _ to replace ., e.g.: name.first -> name_first
  • Attribute of Mixed type is not supported to be query arguments
  • The response is always an Array

Mutation

Create

The mutation of create is create{modelName}, if the attribute of the model is defined as required in Mongoose shema, it is required as well for create mutaion. Using User model for example:

`mutation createMyUser {
  user: createUser(
    userName: "wwayne",
    hobbies: ["This", "is", "Required"],
    currentSchool: "${schoolInstance.id}"
  ) {
    id
    userName
    currentSchool {
     id
    }
  }
}`
Update

The mutation of update is update{modelName}. Currently update only support single document update, which means the argument id is required and plural attribute can't be used as argument unless it is plural originally. For example, userNames is not supposed to be an argument, but hobbies and education could.

Using User model for example:

`mutation updateMyUser {
  user: updateUser(
    id: "${userInstance.id}"
    userName: "wwayne"
  ) {
    id
    userName
  }
}`
Delete

The mutation of delete is delete{modelName}. Currently delete only support single document update, so it only accept id as argument.

The response is { success: {Bool}, msg: {String or null} }

Using User model for example:

`mutation deleteMyUser {
  result: deleteUser(
    id: "${userInstance.id}"
  ) {
    success
    msg
  }
}`

Supported type

All Mongoose types are supported

  • String
  • Number
  • Date
  • Buffer
  • Boolean
  • Mixed (Can't be used as argument in query and mutation)
  • ObjectId (Must be accompanied with ref)
  • Array

In addition, the object type is supported as well, but you have to use _ to replace . when using it as argument, because Graphql only support /.[a-z][A-Z][0-9]/ as name convention for the moment.

Mongoose: name { first: { one: String, two: Number }, last: String }

user (
	name_first_one: "firstOne",
	name_first_two: 21,
	name_last: "nameLast"
) {
	id
}

Extend schema

Mooseql will generate some basic CRUD methods which may not enough for you, then you need to define your own schema.

buildTypes

To make it easy, Mooseql exposes an method called buildTypes which used for converted Mongoose model to Graphql Type

import mooseql, { buildTypes } from 'mooseql'
Extend default schema

See you have two models UserModel and SchoolModel, you can extend schema like following:

import mooseql, { buildTypes } from 'mooseql'

// typeMap = {User: GraphqlUserType, School: GraphqlSchoolType }
const typeMap = buildTypes([UserModel, SchoolModel])

const mySchema = mooseql([UserModel, SchoolModel], {
  mutation: {
    customAddUser: {
      type: typeMap['User'],
      args: {
        userName: { type: new GraphQLNonNull(GraphQLString) },
        hobbies: { type: new GraphQLNonNull(new GraphQLList(GraphQLString)) },
        age: { type: new GraphQLNonNull(GraphQLFloat) }
      },
      resolve: async (_, args) => {
        const instance = new UserModel(args)
        return await instance.save()
      }
    }
  }
})

So it just pass { query: {Your custom queries}, mutation: {Your custom mutations} } into mooseql() as the second argument.

License

MIT

Keywords

FAQs

Package last updated on 16 Sep 2016

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc