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

发布于 2025-01-09 11:06:31 字数 585 浏览 0 评论 0原文

在 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(`
              

In the Apollo docs it shows this example:

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}`)
});

I want to be able to pass in an argument, such as an ID into it, like:

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

Is this possible with Apollo?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情绪失控 2025-01-16 11:06:31

在 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,
})

On Apollo server V3 you need to use a different kind of code. It has some breaking changes from V2.

You can do that by following the code below:

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,
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文