Handling Mongoose Populated Fields in GraphQL

前端 未结 2 1630
陌清茗
陌清茗 2021-02-06 09:16

How do I represent a field that could be either a simple ObjectId string or a populated Object Entity?

I have a Mongoose Schema that represents a \'Device t

2条回答
  •  我寻月下人不归
    2021-02-06 09:57

    As a matter of fact, you can use union or interface type for linked_device field.

    Using union type, you can implement GQAssetType as follows:

    // graphql-asset-type.js
    
    import { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql'
    
    var LinkedDeviceType = new GraphQLUnionType({
      name: 'Linked Device',
      types: [ ObjectIdType, GQAssetType ],
      resolveType(value) {
        if (value instanceof ObjectId) {
          return ObjectIdType;
        }
        if (value instanceof Asset) {
          return GQAssetType;
        }
      }
    });
    
    export var GQAssetType = new GraphQLObjectType({
      name: 'Asset',
      fields: () => ({
        name: { type: GraphQLString },
        linked_device: { type: LinkedDeviceType },
      })
    });
    

    Check out this excellent article on GraphQL union and interface.

提交回复
热议问题