提问者:小点点

如何在GraphQL模式指令中获取字段类型(Node. js、graph ql-tools)


我正在使用一个模式指令,它实现了SchemaDirectiveVisitorvisitFieldDefition函数。我想知道模式中定义的字段的类型,例如该类型是否是数组。

在架构中:

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服务器和graph ql工具。


共2个答案

匿名用户

传递给visitFieldDefition的第一个参数是一个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

如果该字段非空、列表或两者的某种组合,则需要“展开”该类型。您可以随时检查是否有任何包装类型是List:

const { isWrappingType } = require('graphql')

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

匿名用户

我们可以检查graph ql类型

const { GraphQLString } = require('graphql');

const type = field.type

if(field.type === GraphQLString) return 'string'

我如何使用它?我需要用S3根前缀S3对象键URL所以我创建了一个指令来执行此操作,它检查并返回条件字符串和数组。和代码。

const { SchemaDirectiveVisitor } = require('apollo-server');
const { defaultFieldResolver, GraphQLString, GraphQLList } = require('graphql');

class S3Prefix extends SchemaDirectiveVisitor {
  visitFieldDefinition(field) {
    const { resolve = defaultFieldResolver } = field;
    field.resolve = async function (...args) {
      const result = await resolve.apply(this, args);

      if (field.type === GraphQLString) {
        if (result) {
          return [process.env.AWS_S3_PREFIX, result].join('');
        } else {
          return null;
        }
      }

      if (field.type === GraphQLList) {
        if (result) {
          return result.map((key) => [process.env.AWS_S3_PREFIX, key].join(''));
        } else {
          return [];
        }
      }
    };
  }
}

module.exports = S3Prefix;