react 项目中使用 graphql mock 功能时返回所有数据问题

来源:8-8 【阶段练练练】手机端账号密码注册与登录

慕粉3946981

2023-11-15

import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { addMocksToSchema } from '@graphql-tools/mock';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { faker } from '@faker-js/faker/locale/zh_CN'

// 定义 graphql schema 字符串
const typeDefs = `#graphql
type UserType {
  id: String!
  name: String!
  desc: String!

  """登录的账户名称"""
  account: String!
}

type Query {
  """根据 id 参数查询相应用户"""
  find(id: String!): UserType
}

type Mutation {
  """根据参数创建一个用户"""
  create(params: UserInput!): Boolean!

  """根据 id 参数和新的用户数据来更新用户"""
  update(id: String!, params: UserInput!): Boolean!

  """根据 id 参数删除相应的一个用户"""
  del(id: String!): Boolean!
}

input UserInput {
  name: String!

  """描述"""
  desc: String!
}
`;

// 定义返回什么数据
const resolvers = {
  Query: {
    find: (_, args) => {
      console.log('mock 查询操作参数 args', args)
      return {
        name: faker.person.fullName(),
      }
    }
  },
};

// 定义不同的数据类型 mock 数据
const mocks = {
  Int: () => 6,
  Float: () => 22.1,
  String: () => '默认 string 类型返回的 mock 字符串',
};

const server = new ApolloServer({
  schema: addMocksToSchema({
    schema: makeExecutableSchema({ typeDefs, resolvers }),
    mocks,
    preserveResolvers: true,
  }),
});

const { url } = await startStandaloneServer(server, { listen: { port: 8888 } });

console.log(`🚀 Server listening at: ${url}`);

请问在resolvers 的 Query 或者 Mutation 中定义的函数,可以让其返回部分数据吗?
举例,Query 对象中的 find 函数默认返回4个字段的数据,我只想让其 mock 出两个字段数据。

写回答

1回答

黑石

2023-11-15

可以的,你只要把 usertype 改成两个字段,或者新增加一个类型,只有两个字段,作为 query find 的返回值就可以了。

0
9
慕粉3946981
非常感谢!
2023-11-15
共9条回复

React18+TS+NestJS+GraphQL 全栈开发在线教育平台

平台级应用+流行全栈技术+实用职场技巧&面试策略 助你升职加薪

438 学习 · 241 问题

查看课程