Как получить тип поля в директиве схемы GraphQL (Node.js, graphql-tools) - PullRequest
0 голосов
/ 13 февраля 2019

Я использую директиву схемы, которая реализует функцию visitFieldDefinition SchemaDirectiveVisitor.Я хочу знать тип поля, определенного в схеме, и, например, если тип является массивом.

В схеме:

type DisplayProperties {
  description: StringProperty @property
  descriptions: [StringProperty]! @property
}

Директива свойства:

class PropertyDirective extends SchemaDirectiveVisitor {
  visitFieldDefinition(field) {
    // how to check that field type is StringProperty?

    // how to find out that the field type is an array?
  }
}

Использование сервера Apollo и graphql-tools.

1 Ответ

0 голосов
/ 13 февраля 2019

Первый параметр, переданный visitFieldDefinition, является GraphQLField объектом:

interface GraphQLField<TSource, TContext, TArgs = { [key: string]: any }> {
    name: string;
    description: Maybe<string>;
    type: GraphQLOutputType;
    args: GraphQLArgument[];
    resolve?: GraphQLFieldResolver<TSource, TContext, TArgs>;
    subscribe?: GraphQLFieldResolver<TSource, TContext, TArgs>;
    isDeprecated?: boolean;
    deprecationReason?: Maybe<string>;
    astNode?: Maybe<FieldDefinitionNode>;
}

Таким образом, чтобы получить тип, вы можете просто сделать:

const type = field.type

Если полеэто не нуль, список или некоторая комбинация двух, вам нужно "развернуть" тип.Вы можете проверить, является ли какой-либо из типов оболочек списком, по мере появления:

const { isWrappingType } = require('graphql')

let isList = false
let type = field.type
while (isWrappingType(type)) {
  if (type.name === 'GraphQLList') {
    isList = true
  }
  type = type.ofType
}
...