Security News
Bun 1.2 Released with 90% Node.js Compatibility and Built-in S3 Object Support
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
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.
npm install mongoose --save
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)
import mooseql from 'mooseql'
const mySchema = mooseql([UserModel])
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
}
}
}`
})
{
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' }]
}
`{ 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
}
}
}`
name -> names
_
to replace .
, e.g.: name.first
-> name_first
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
}
}
}`
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
}
}`
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
}
}`
All Mongoose types are supported
ref
)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
}
Mooseql will generate some basic CRUD methods which may not enough for you, then you need to define your own schema.
To make it easy, Mooseql exposes an method called buildTypes
which used for converted Mongoose model to Graphql Type
import mooseql, { buildTypes } from 'mooseql'
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.
In practice, we store the session in req.session or logged in user data in req.user, and it is usually passed to graphql as context. In this situation, you just need to add an option context
in your Mongoose schema. Let's using express + express-graphql + password + express-session for example.
See you have a model named Article, the author is logged in user, so Mongoose schema may like the following:
const articleSchema = new Schema({
title: String,
author: {
type: Schema.Types.ObjectId,
required: true,
ref: 'User',
context: 'user.id'
}
})
Since express-graphql will use request
object as context if nothing set to context, and passport will set user object into req.user
, express-session will use req.session
. So your context is probably like
{
user: userObject,
session: sessionObject
}
That's why you set context: 'user.id'
in your Mongoose schema, because the path author
only store an ObjectId, so it only cares about user.id
instead of the completed user object.
In this way, after user login, when you create an new article, you don't need to pass the autor as params even though it has been set to required
, the author will be got from req.user.id
automatically. The query string is like:
`mutation create {
article: createArticle (
title: "How to use graphql"
) {
id
title
author {
id
userName
}
}
}`
MIT
FAQs
Build GraphQL Schema based on Mongoose model
The npm package mooseql receives a total of 16 weekly downloads. As such, mooseql popularity was classified as not popular.
We found that mooseql demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
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.
Security News
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
Security News
Biden's executive order pushes for AI-driven cybersecurity, software supply chain transparency, and stronger protections for federal and open source systems.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.