连接 Apollo 和 mongodb [英] Connect Apollo with mongodb

查看:24
本文介绍了连接 Apollo 和 mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的 Apollo 服务器与我的 mongoDB 连接起来.我知道那里有很多例子,但我被困在异步部分并且没有找到解决方案或例子(这很奇怪,我完全错了吗?)

I want to connect my Apollo server with my mongoDB. I know there are many examples out there, but I get stuck at the async part and did not found a solution or example for that (that's strange, am I completly wrong?)

我从 next.js 的例子开始 https://github.com/zeit/next.js/tree/master/examples/api-routes-apollo-server-and-client.但是缺少 mongodb 集成.

I started with the example from next.js https://github.com/zeit/next.js/tree/master/examples/api-routes-apollo-server-and-client . But the mongodb integration is missing.

pages/api/graphql.js

    import {ApolloServer} from 'apollo-server-micro';
    import {schema} from '../../apollo/schema';

    const apolloServer = new ApolloServer({schema});

    export const config = {
        api: {
            bodyParser: false
        }
    };

    export default apolloServer.createHandler({path: '/api/graphql'});

apollo/schema.js

    import {makeExecutableSchema} from 'graphql-tools';
    import {typeDefs} from './type-defs';
    import {resolvers} from './resolvers';

    export const schema = makeExecutableSchema({
        typeDefs,
        resolvers
    });

apollo/resolvers.js

    const Items = require('./connector').Items;
    export const resolvers = {
        Query: {
            item: async (_parent, args) => {
                const {id} = args;
                const item = await Items.findOne(objectId(id));
                return item;
            },
            ...
        }
    }

apollo/connector.js

    require('dotenv').config();
    const MongoClient = require('mongodb').MongoClient;

    const password = process.env.MONGO_PASSWORD;
    const username = process.env.MONGO_USER;
    const uri = `mongodb+srv://${username}:${password}@example.com`;

    const client = await MongoClient.connect(uri);
    const db = await client.db('databaseName')
    const Items = db.collection('items')

    module.exports = {Items}

所以问题在于connector.js 中的await.我不知道如何在异步函数中调用它,也不知道如何以其他方式将 MongoClient 提供给解析器.如果我只是删除 await,它会返回 – 显然 – 一个挂起的承诺,并且不能在其上调用函数 .db('databaseName').

So the problem is the await in connector.js. I have no idea how to call this in an async function or how to provide the MongoClient on an other way to the resolver. If I just remove the await, it returns – obviously – an pending promise and can't call the function .db('databaseName') on it.

推荐答案

不幸的是,我们距离 顶级等待.

Unfortunately, we're still a ways off from having top-level await.

您可以通过将其余代码放在 Promise 的 then 回调中来延迟运行其余代码,直到 Promise 解决.

You can delay running the rest of your code until the Promise resolves by putting it inside the then callback of the Promise.

async function getDb () {
  const client = await MongoClient.connect(uri)
  return client.db('databaseName')
}

getDb()
  .then(db => {
    const apollo = new ApolloServer({
      schema,
      context: { db },
    })
    apollo.listen()
  })
  .catch(e => {
    // handle any errors
  })

或者,您可以在第一次需要时创建连接并缓存它:

Alternatively, you can create your connection the first time you need it and just cache it:

let db

const apollo = new ApolloServer({
  schema,
  context: async () => {
    if (!db) {
      try {
        const client = await MongoClient.connect(uri)
        db = await client.db('databaseName')
      catch (e) {
        // handle any errors
      }
    }
    return { db }
  },
})
apollo.listen()

这篇关于连接 Apollo 和 mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆