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

apollo-datasources-mongodb

v3.0.2

Published

Apollo data source for MongoDB

Downloads

46

Readme

Fork from apollo-datasource-mongodb

Apollo data source for MongoDB

npm i apollo-datasources-mongodb

This package uses DataLoader for batching and per-request memoization caching. It also optionally (if you provide a ttl) does shared application-level caching (using either the default Apollo InMemoryLRUCache or the cache you provide to ApolloServer()). It does this for the following methods:

Usage

Basic

The basic setup is subclassing MongoDataSource, passing your collection or Mongoose model to the constructor, and using the API methods:

data-sources/Users.js

import { MongoDataSource } from 'apollo-datasource-mongodb'

export default class Users extends MongoDataSource {
  getUser(userId) {
    return this.findOneById(userId)
  }
}

and:

import { MongoClient } from 'mongodb'

import Users from './data-sources/Users.js'

const client = new MongoClient('mongodb://localhost:27017/test')
client.connect()

const server = new ApolloServer({
  typeDefs,
  resolvers,
  dataSources: () => ({
    users: new Users(client.db().collection('users'))
    // OR
    // users: new Users(UserModel)
  })
})

Inside the data source, the collection is available at this.collection (e.g. this.collection.update({_id: 'foo, { $set: { name: 'me' }}})). The model (if you're using Mongoose) is available at this.model (new this.model({ name: 'Alice' })). The request's context is available at this.context. For example, if you put the logged-in user's ID on context as context.currentUserId:

class Users extends MongoDataSource {
  ...

  async getPrivateUserData(userId) {
    const isAuthorized = this.context.currentUserId === userId
    if (isAuthorized) {
      const user = await this.findOneById(userId)
      return user && user.privateData
    }
  }
}

If you want to implement an initialize method, it must call the parent method:

class Users extends MongoDataSource {
  initialize(config) {
    super.initialize(config)
    ...
  }
}

If you're passing a Mongoose model rather than a collection, Mongoose will be used for data fetching. All transformations defined on that model (virtuals, plugins, etc.) will be applied to your data before caching, just like you would expect it. If you're using reference fields, you might be interested in checking out mongoose-autopopulate.

Batching

This is the main feature, and is always enabled. Here's a full example:

class Users extends MongoDataSource {
  getUser(userId) {
    return this.findOneById(userId)
  }
}

class Posts extends MongoDataSource {
  getPosts(postIds) {
    return this.findManyByIds(postIds)
  }
}

const resolvers = {
  Post: {
    author: (post, _, { dataSources: { users } }) => users.getUser(post.authorId)
  },
  User: {
    posts: (user, _, { dataSources: { posts } }) => posts.getPosts(user.postIds)
  }
}

const server = new ApolloServer({
  typeDefs,
  resolvers,
  dataSources: () => ({
    users: new Users(db.collection('users')),
    posts: new Posts(db.collection('posts'))
  })
})

Caching

To enable shared application-level caching, you do everything from the above section, and you add the ttl (in seconds) option to findOneById():

const MINUTE = 60

class Users extends MongoDataSource {
  getUser(userId) {
    return this.findOneById(userId, { ttl: MINUTE })
  }

  updateUserName(userId, newName) {
    this.deleteFromCacheById(userId)
    return this.collection.updateOne({
      _id: userId
    }, {
      $set: { name: newName }
    })
  }
}

const resolvers = {
  Post: {
    author: (post, _, { users }) => users.getUser(post.authorId)
  },
  Mutation: {
    changeName: (_, { userId, newName }, { users, currentUserId }) =>
      currentUserId === userId && users.updateUserName(userId, newName)
  }
}

Here we also call deleteFromCacheById() to remove the user from the cache when the user's data changes. If we're okay with people receiving out-of-date data for the duration of our ttl—in this case, for as long as a minute—then we don't need to bother adding calls to deleteFromCacheById().

TypeScript

Since we are using a typed language, we want the provided methods to be correctly typed as well. This requires us to make the MongoDataSource class polymorphic. It requires 1-2 template arguments. The first argument is the type of the document in our collection. The second argument is the type of context in our GraphQL server, which defaults to any. For example:

data-sources/Users.ts

import { MongoDataSource } from 'apollo-datasource-mongodb'
import { ObjectId } from 'mongodb'

interface UserDocument {
  _id: ObjectId
  username: string
  password: string
  email: string
  interests: [string]
}

// This is optional
interface Context {
  loggedInUser: UserDocument
}

export default class Users extends MongoDataSource<UserDocument, Context> {
  getUser(userId) {
    // this.context has type `Context` as defined above
    // this.findOneById has type `(id: ObjectId) => Promise<UserDocument | null | undefined>`
    return this.findOneById(userId)
  }
}

and:

import { MongoClient } from 'mongodb'

import Users from './data-sources/Users.ts'

const client = new MongoClient('mongodb://localhost:27017/test')
client.connect()

const server = new ApolloServer({
  typeDefs,
  resolvers,
  dataSources: () => ({
    users: new Users(client.db().collection('users'))
    // OR
    // users: new Users(UserModel)
  })
})

API

The type of the id argument must match the type used in the database. We currently support ObjectId and string types.

findOneById

this.findOneById(id, { ttl })

Resolves to the found document. Uses DataLoader to load id. DataLoader uses collection.find({ _id: { $in: ids } }). Optionally caches the document if ttl is set (in whole positive seconds).

findManyByIds

this.findManyByIds(ids, { ttl })

Calls findOneById() for each id. Resolves to an array of documents.

findByFields

this.findByFields(fields, { ttl })

Resolves to an array of documents matching the passed fields. If an empty object is passed as the fields parameter, resolves to an array containing all documents in the given collection.

fields has this type:

interface Fields {
  [fieldName: string]:
    | string
    | number
    | boolean
    | ObjectId
    | (string | number | boolean | ObjectId)[]
}

Examples

// get user by username
// `collection.find({ username: $in: ['testUser'] })`
this.findByFields({
  username: 'testUser'
})

// get all users with either the "gaming" OR "games" interest
// `collection.find({ interests: $in: ['gaming', 'games'] })`
this.findByFields({
  interests: ['gaming', 'games']
})

// get user by username AND with either the "gaming" OR "games" interest
// `collection.find({ username: $in: ['testUser'], interests: $in: ['gaming', 'games'] })`
this.findByFields({
  username: 'testUser',
  interests: ['gaming', 'games']
})

deleteFromCacheById

this.deleteFromCacheById(id)

Deletes a document from the cache that was fetched with findOneById or findManyByIds.

deleteFromCacheByFields

this.deleteFromCacheByFields(fields)

Deletes a document from the cache that was fetched with findByFields. Fields should be passed in exactly the same way they were used to find with.