Graphql mock 方案

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

我们期望基于 TS 强类型定义的特点以及中后台常见列表、详情的数据类型共性,实现对 GraphQL API 的数据 mock,减少手写 mock 每个 API 数据。

手写 mock  举例:           

 const list = new UserList()
    list.data = Array(10)
      .fill(1)
      .map((_, i) => {
        const item = new UserInfo()

        item.id = new Int64(i)
        ...

    }

期望通过统一的 mock API

  • 减少对每个API 数据的手动 mock
  • 与 dto 中的类型定义完全一致,从而避免了手写时的误写

基于此,调研到以下三种方案:

方案1:  使用 graphql-tools 进行 mock
// https://graphql.cn/blog/mocking-with-graphql/ 文档demo
// > npm install graphql-tools

import { mockServer } from 'graphql-tools';
import from './mySchema.graphql';
 
const myMockServer = mockServer(schema);
myMockServer.query(`{
  allUsers: {
    id
    name
  }
}`);
 
// returns
// {
//   data: {
//     allUsers:[
//       { id: 'ee5ae76d-9b91-4270-a007-fad2054e2e75', name: 'lorem ipsum' },
//       { id: 'ca5c182b-99a8-4391-b4b4-4a20bd7cb13a', name: 'quis ut' }
//     ]
//   }
// }
  • 另一种实现方式
import { graphql } from 'graphql'
import { addMocksToSchema } from '@graphql-tools/mock'
import { makeExecutableSchema } from '@graphql-tools/schema'
 
// Fill this in with the schema string
const schemaString = `...`
 
// Make a GraphQL schema with no resolvers
const schema = makeExecutableSchema({ typeDefs: schemaString })
 
// Create a new schema with mocks
const schemaWithMocks = addMocksToSchema({ schema })
 
const query = /* GraphQL */ `
  query tasksForUser {
    user(id: 6) {
      id
      name
    }
  }
`
 
graphql({
  schema: schemaWithMocks,
  source: query
}).then(result => console.log('Got result', result))
方案2:  ts定义 => json schema => mock 数据
  • ts定义 => json schema => mock 数据(利用现成库)
方案3:  通过解析 Class 生成 mock 数据
  • 使用 Reflect 获取 class 类中的元数据信息,结合 mockjs 库生成模拟数据

参考链接:

https://github.com/ducafecat/graphQL-example/blob/master/src/mock.js

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值