首页 > 解决方案 > 你能在graphql中请求一个文字值吗?

问题描述

我试图弄清楚当客户端领先于服务器时如何模拟请求。我希望能够只请求文字,以便稍后返回并更改它们,有没有办法做这样的事情?

query myQuery {
  type {
    fieldName: 42
  }
}

标签: graphql

解决方案


是的,如果您至少设置了服务器样板代码,那么设置模拟响应非常容易。如果您使用的是 Apollo,则有内置工具可以方便地进行模拟。

https://www.apollographql.com/docs/graphql-tools/mocking.html

从文档:

GraphQL API 的强类型特性非常适合模拟。这是 GraphQL-First 开发过程的重要组成部分,因为它使前端开发人员能够构建 UI 组件和功能,而无需等待后端实现。

这是文档中的一个示例:

import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';
import { graphql } from 'graphql';

// Fill this in with the schema string
const schemaString = `...`;

// Make a GraphQL schema with no resolvers
const schema = makeExecutableSchema({ typeDefs: schemaString });

// Add mocks, modifies schema in place
addMockFunctionsToSchema({ schema });

const query = `
query tasksForUser {
  user(id: 6) { id, name }
}
`;

graphql(schema, query).then((result) => console.log('Got result', result));

这个模拟逻辑只是查看你的模式,并确保返回一个字符串,其中你的模式有一个字符串、一个数字代表一个数字等。所以你已经可以得到正确的结果形状。但是,如果您想使用模拟来进行复杂的测试,您可能希望将它们定制为您的特定数据模型。


推荐阅读