mongodb Apollo Server Express v4 GraphQL此.findOneById不是函数

zengzsys  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(153)

我有以下ApolloServer(v4)

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

export default class LoaderAsset extends MongoDataSource {
 async getAsset(assetId) {
    return this.findOneById(assetId) // ERROR IS HERE
  }
}

async function startApolloServer(app) {
  const httpServer = http.createServer(app);

  const server = new ApolloServer({
    typeDefs,
    resolvers,
    plugins: [ApolloServerPluginDrainHttpServer({ httpServer })]

  });

  await server.start();
  app.use(
    '/graphql',
    cors(),
    bodyParser.json(),
    expressMiddleware(server, {
      context: async ({ req }) => {
       return {
        dataSources: {
          loaderAsset: new LoaderAsset(modelAsset),
        }
      }
      },
    }),
  );

  const port = config.get('Port') || 8081;
  await new Promise(resolve => httpServer.listen({ port }, resolve));
}

当我运行graphql并发送一个assetId时,一切都正常,直到我收到以下错误:
this.findOneById不是函数顺便说一下**(this)集合模型**对象,但没有任何方法。
是否因为apollo-datasource-mongodb与新版本的apollo服务器v4不兼容?
v3中的数据源如下所示:

dataSources: () => ({
    users: new Users(client.db().collection('users'))
    // OR
    // users: new Users(UserModel)
  })

但在新版本中,dataSources位于上下文内部。问题可能是由于此更改。

toiithl6

toiithl61#

贷记至:https://github.com/GraphQLGuide/apollo-datasource-mongodb/issues/114上的https://github.com/systemkrash
我所做的就是重写我的datasource类,这样我就可以调用MongoDatasource类里面的initialize方法了。现在它对我有用了。

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

class ReceptionDataSource extends MongoDataSource {
  constructor({ collection, cache }) {
    super(collection);
    super.initialize({ context: this.context, cache });
  }

  async getReception(receptionId) {
    return await this.findOneById(receptionId);
  }
}

export default ReceptionDataSource;
then in my context

async function startApolloServer(app) {
  const httpServer = http.createServer(app);

  const server = new ApolloServer({
    typeDefs,
    resolvers,
    plugins: [ApolloServerPluginDrainHttpServer({ httpServer })]

  });

  await server.start();
  app.use(
    '/graphql',
    cors(),
    bodyParser.json(),
    expressMiddleware(server, {
      context: async ({ req }) => {
      const { cache } = server
       return {
        dataSources: {
          loaderAsset: new ReceptionDataSource({collection: ReceptionModel, cache}),
        }
      }
      },
    }),
  );

  const port = config.get('Port') || 8081;
  await new Promise(resolve => httpServer.listen({ port }, resolve));
}

相关问题