npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

joiql-mongo

v1.0.10

Published

Data modeling library using JoiQL and Mongo

Downloads

12

Readme

joiql-mongo

GraphQL and MongoDB modeling library using JoiQL.

Example

const { connect, model, models, string, date } = require('joiql-mongo')
connect('mongodb://localhost:27017/gluu')

const user = model('user', {
  name: string()
    .meta((is) => ({
      create: is.required()
    })),
  email: string().email()
})

const tweet = model('tweet', {
  body: string()
    .meta((is) => ({
      'create update': is.required().max(150)
    }))
  createdAt: date()
    .meta((is) => ({
      'create read update delete list': is.forbidden().default(new Date())
    }))
})

tweet.on('create', (ctx, next) => {
  next().then(() =>
    console.log('Congrats on the tweet', ctx.res.createTweet.body)
  )
})

const api = models(tweet, user)
graphql(api.schema, ...)

API

connect(uri)

Connects to a MongoDB database and returns a promised-mongojs instance.

const { connect } = require('joiq-mongo')
const db = connect('mongodb://localhost:27017/mydb')

model(name, schema)

Create an instance of a model that can be automatically converted into GraphQL schemas for CRUDL operations. Pass in the model name and an object of Joi types.

const { model, string, array, objectid } = require('joiq-mongo')
const user = model('user', {
  name: string(),
  email: string().email(),
  friends: array().items(objectid())
})

As you can see above, JoiQL Mongo exports Joi types for your convenience. There is even a custom objectid type that validates and typecasts strings to ObjectId instances.

model.on(method, middlewareFunction)

Hook into CRUDL operations of a model through JoiQL middleware. JoiQL Mongo will automatically add persistence middleware (e.g. db.save or db.find operations) to the bottom of the stack. This way you can hook into before and after persistence operations by running code before or after control flows upstream using await next().

For those faimiliar with Rails, you can think of these as the equivalent of ActiveRecord callbacks.

user.on('update', async (ctx, next) => {
  await next()
  if (ctx.res.updateUser.password) sendConfirmationEmail()
})

JoiType.meta(decoratorFunction)

JoiQL Mongo allows for conditional validation via a DSL leveraging the meta API in Joi. Pass a function that returns an object describing the conditional validation.

See below how we use the key 'create update' to specify that a user's name is required with a minimum of 2 characters when running a createUser or updateUser GraphQL operation. The keys of this object can be any combination of create read update delete list joined by spaces, and the values extend the attribute passed in as the first argument to the function.

model('user', {
  name: string().meta((is) => ({
    'create update': is.required().min(2)
  }))
})

model.create(attrs) => Promise

Convenience method for running a "create" operation that leverages validation and middleware.

user.create({ name: 'Foo' })
  .catch(() => console.log('validation failed'))
  .then(() => console.log('successfully created user'))

model.find(attrs) => Promise

Convenience method for running a "read" operation that leverages validation and middleware.

user.find({ name: 'Foo' })
  .catch(() => console.log('validation failed'))
  .then(() => console.log('successfully created user'))

model.update(attrs) => Promise

Convenience method for running an "update" operation that leverages validation and middleware.

user.update({ _id: "543d3fb87261692e99a80500", name: 'Foo' })
  .catch(() => console.log('validation failed'))
  .then(() => console.log('successfully created user'))

model.destroy(attrs) => Promise

Convenience method for running a "delete" operation that leverages validation and middleware.

user.destroy({ _id: "543d3fb87261692e99a80500", name: 'Foo' })
  .catch(() => console.log('validation failed'))
  .then(() => console.log('successfully created user'))

model.where(attrs) => Promise

Convenience method for running a "list" operation that leverages validation and middleware.

user.where({ name: 'Foo' })
  .catch(() => console.log('validation failed'))
  .then(() => console.log('successfully created user'))

query(name, schema, middleware)

Convenience utility for adding add-hoc GraphQL queries.

const { query, string, array } = require('joiql-mongo')
query('tags', array().items(string()), async (ctx, next) => {
  ctx.res.tags = await Tags.find()
})

mutation(name, schema, middleware)

Convenience utility for adding add-hoc GraphQL mutations.

const { mutation, string, array } = require('joiql-mongo')
mutation('emailBlast', string().meta({ args: {
  emails: array().items(string().email())
} }), async (ctx, next) => {
  await sendEmail()
  ctx.res.emailBlast = 'success'
  next()
})

models(...models)

Combine a set of models into a JoiQL instance that exposes a GraphQL.js schema object.

const { models } = require('joiql-mongo')
//...
const api = models(tweet, user)
app.use('/graphql', graphqlHTTP({ schema: api.schema }))

graphqlize({ modelName: modelObject })

Convenience utility for converting a hash of model objects into mountable Koa middleware

const { graphqlize } = require('joiql-mongo')
const models = require('./models')
const mount = require('koa-mount')

const app = new Koa()

app.use(mount('/graphql', graphqlize(models))))

Contributing

Please fork the project and submit a pull request with tests. Install node modules npm install and run tests with npm test.

License

MIT