如何描述嵌套对象的类型?如何描述联合类型?

How to descibe type for nested object ? How to Describe union types?

我正在尝试为查询编写 typeDef。

import {gql} from "@apollo/client";

const typeDefs = gql`
    
    type Query{
        rockets:[Rocket]!
        rocket(id:ID):Rocket!
    }
    type Rocket {
        id:ID!
        name:String!
        mass:RocketMass
    }
    type MassInt{
        kg:Int
    }    
    type MassFloat{
        kg:Float
    }
    
    union Mass = MassInt|MassFloat

    type RocketMass {
        kg: Mass
        lb: Mass
    }

`
export {typeDefs}

当我编写“GET_ROCKET”查询时,我在 IDE.

中遇到错误
import {gql} from "@apollo/client";

const GET_ROCKETS = gql`
    query GetRockets {
        rockets{
            id,
            name
        }
    }
`
const GET_ROCKET = gql`
    query GetRocket($id:ID!){
        rocket(id: $id){
        mass {
            kg,
            lb
        }
        name
    }
    }
`
export {GET_ROCKETS, GET_ROCKET}

谁能解释我如何使用我的 typedef 中描述的属性“kg”和“lb”,以及为什么我不能像这样编写联合? union Mass2 = Int|Float

MassInt.kgMassFloat.kg字段需要取不同的名字,否则会报冲突错误。

参见union types官方文档。

正确的 typeDefsGET_ROCKET GraphQL 查询应该是这样的:

import express from 'express';
import { ApolloServer, gql } from 'apollo-server-express';
import faker from 'faker';
const app = express();

const typeDefs = gql`
  type Query {
    rockets: [Rocket]!
    rocket(id: ID): Rocket!
  }
  type Rocket {
    id: ID!
    name: String!
    mass: RocketMass
  }
  type MassInt {
    int: Int
  }
  type MassFloat {
    float: Float
  }

  union Mass = MassInt | MassFloat

  type RocketMass {
    kg: Mass
    lb: Mass
  }
`;

const resolvers = {
  Query: {
    rocket: (_, { id }) => {
      return {
        id: 1,
        name: faker.lorem.word(),
        mass: {
          kg: { int: 100 },
          lb: { float: 10.1 },
        },
      };
    },
  },
  Mass: {
    __resolveType: (obj) => {
      if (isInt(obj.int)) {
        return 'MassInt';
      }
      if (isFloat(obj.float)) {
        return 'MassFloat';
      }
      return null;
    },
  },
};

function isInt(n) {
  return Number(n) === n && n % 1 === 0;
}

function isFloat(n) {
  return Number(n) === n && n % 1 !== 0;
}
const server = new ApolloServer({ typeDefs, resolvers });
const port = 4000;
server.applyMiddleware({ app, path: '/graphql' });
app.listen(port, () => console.log(`Apollo server started at http://localhost:${port}`));
query GetRocket($id: ID){
  rocket(id: $id){
    id
    name
    mass {
      kg {
        ... on MassInt {
          int
        }
        ... on MassFloat {
          float
        }
      }
      lb {
        ... on MassInt {
          int
        }
        ... on MassFloat {
          float
        }
      }
    }
  }
}

查询结果:

{
  "data": {
    "rocket": {
      "id": "1",
      "name": "modi",
      "mass": {
        "kg": {
          "int": 100
        },
        "lb": {
          "float": 10.1
        }
      }
    }
  }
}