是否可以在 Apollo 模拟中传递参数?

Is it possible to pass arguments in Apollo mocks?

在 Apollo docs 中显示了这个例子:

const { ApolloServer, gql } = require('apollo-server');

const typeDefs = gql`
  type Query {
    hello: String
    resolved: String
  }
`;

const resolvers = {
  Query: {
    resolved: () => 'Resolved',
  },
};

const mocks = {
  Int: () => 6,
  Float: () => 22.1,
  String: () => 'Hello',
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  mocks,
});

server.listen().then(({ url }) => {
  console.log(` Server ready at ${url}`)
});

我希望能够传入一个参数,例如 ID,例如:

const mocks = {
  Job: (id) => {
      return somearray.filter(_id === id)
  },
};

A​​pollo 可以吗?

在 Apollo 服务器 V3 上,您需要使用不同类型的代码。它与 V2 相比有一些重大变化。

您可以按照以下代码执行此操作:

import { buildClientSchema } from 'graphql';
import { addMocksToSchema } from '@graphql-tools/mock';
import { makeExecutableSchema } from '@graphql-tools/schema';

const schema = buildClientSchema(myGqlSchemaJson);


const executableSchema = makeExecutableSchema({
  typeDefs: schema,
});

const schemaWithMocks = addMocksToSchema({
  schema: executableSchema,
  resolvers: {
    Query: {
      myCustomQuery: (_parent: any, args: any, teste: any) => {
        if (args.url === '/stack-overflow') {
          return {data: 'Cool website', url: args.url}
        }
      },
    },
  },
});


const server = new ApolloServer({
  schema: schemaWithMocks,
})