Processing Mongoose mail fields in GraphQL

How can I imagine a field that can be either a simple string ObjectIdor a populated Object Entity?

I have a Mongoose scheme, which is a "Device Type" as follows

// assetSchema.js

import * as mongoose from 'mongoose'
const Schema = mongoose.Schema;

var Asset = new Schema({  name : String,
                          linked_device: { type: Schema.Types.ObjectId, 
                                           ref: 'Asset'})

export AssetSchema = mongoose.model('Asset', Asset);

I am trying to simulate this as GraphQLObjectType, but I do not understand how to allow a field linked_ueto accept two types of values, one of which is ObjectIdand the other is a complete object Asset(when it is full)

// graphql-asset-type.js

import { GraphQLObjectType, GraphQLString } from 'graphql'

export var GQAssetType = new GraphQLObjectType({
           name: 'Asset',
           fields: () => ({
               name: GraphQLString,
               linked_device: ____________    // stumped by this
});

I looked at Union types, but the problem is that the Union type expects fields to be defined as part of its definition, whereas in the case above, there are no fields under the field linked_devicewhen it linked_devicematches a simple one ObjectId.

Any ideas?

+4
2

union interface linked_device.

, GQAssetType :

// 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 },
  })
});

GraphQL.

+4

, . , , , ObjectId Object, , , , , . , , - Id, . , Unions , , , . , ...

. graphql, . , User Type, :

type User {
    _id: ID
    firstName: String
    lastName: String
    companyId: ID
    company: Company
}

:

  User: {   // <-- this refers to the User Type in Graphql
    company(u) {   // <-- this refers to the company field
      return User.findOne({ _id: u.companyId }); // <-- mongoose User type
    },
  }

User resolver GQL :

query getUserById($_id:ID!) 
    { getUserById(_id:$_id) {
    _id
    firstName
    lastName
    company {
        name
    }
    companyId
    }}

,

S. Arora

+3

Source: https://habr.com/ru/post/1665454/


All Articles