mongoose-dataloader
TypeScript icon, indicating that this package has built-in type declarations

0.3.1 • Public • Published

🖇 Mongoose DataLoader

Helps to avoid declaring DataLoader every Mongoose model.

What is the DataLoader?

  • DataLoader

    DataLoader is a generic utility to be used as part of your application's data fetching layer to provide a simplified and consistent API over various remote data sources such as databases or web services via batching and caching.

Install

$ yarn add mongoose-dataloader

Usage

Step 1. Create mongooseDataloader per request

import { ApolloServer } from 'apollo-server'
import { mongooseDataloader } from 'mongoose-dataloader'

const apolloServer = new ApolloServer({
  // ...
  async context(/* ... */) {
    // ...

    const mongo = mongooseDataloader()

    return {
      mongo,
    }
  },
})

Step 2. Use it with mongoose.model

import mongoose from 'mongoose'

// Mongoose model declaration
const Article = mongoose.model(
  'Article',
  new Schema({
    user: {
      type: String,
      required: true,
    },
    deleted: {
      type: Boolean,
      required: true,
    },
  })
)

// Use it
const resolvers = {
  Something: {
    async someField(parent, args, ctx) {
      // ...

      const article = await ctx.mongo
        .use(Article, {
          key: '_id',
        })
        .load(/* ... */)

      // or with some additional conditions
      const article = await ctx.mongo
        .use(Article, {
          key: '_id',
          where: {
            user: 'SOME_USER_ID',
            deleted: false,
          },
        })
        .load(/* ... */)
    },
  },
}

References

License

Apache 2.0

Readme

Keywords

none

Package Sidebar

Install

npm i mongoose-dataloader

Weekly Downloads

2

Version

0.3.1

License

Apache-2.0

Unpacked Size

19.3 kB

Total Files

6

Last publish

Collaborators

  • tonyfromundefined