graphql - 你能在graphql中请求一个文字值吗?
问题描述
我试图弄清楚当客户端领先于服务器时如何模拟请求。我希望能够只请求文字,以便稍后返回并更改它们,有没有办法做这样的事情?
query myQuery {
type {
fieldName: 42
}
}
解决方案
是的,如果您至少设置了服务器样板代码,那么设置模拟响应非常容易。如果您使用的是 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));
这个模拟逻辑只是查看你的模式,并确保返回一个字符串,其中你的模式有一个字符串、一个数字代表一个数字等。所以你已经可以得到正确的结果形状。但是,如果您想使用模拟来进行复杂的测试,您可能希望将它们定制为您的特定数据模型。
推荐阅读
- firebase - 及时从 Firestore 中检索数据
- javascript - 如何在不点击下载链接的情况下从 react-pdf 生成下载的 pdf?
- laravel - 我可以将数据透视表数据合并到父对象中吗?
- javascript - 我可以编辑 MongoDB 对象并取消它的先前值吗?
- html - 使用引导类在具有不同断点的同一行上设置图像和文本的顺序
- r - 从R中的ggplot过滤geom_lines?
- javascript - 使用 JWT (nodeJS) 检查身份验证
- bash - 如何在同一行中制作两个回显字符串?
- c - GCC 产生一个空的 _start 函数
- java - 从杰克逊迁移到 JSON-B