首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获取GraphQL模式指令中的字段类型(Node.js,graphql-tools)

如何获取GraphQL模式指令中的字段类型(Node.js,graphql-tools)
EN

Stack Overflow用户
提问于 2019-02-13 23:47:06
回答 2查看 782关注 0票数 1

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

在架构中:

代码语言:javascript
复制
type DisplayProperties {
  description: StringProperty @property
  descriptions: [StringProperty]! @property
}

property指令:

代码语言:javascript
复制
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工具。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-02-14 00:37:09

传递给visitFieldDefinition的第一个参数是一个GraphQLField对象:

代码语言:javascript
复制
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>;
}

因此,要获取类型,您只需执行以下操作:

代码语言:javascript
复制
const type = field.type

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

代码语言:javascript
复制
const { isWrappingType } = require('graphql')

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

Stack Overflow用户

发布于 2021-03-10 12:05:53

我们可以使用以下命令检查graphql类型

代码语言:javascript
复制
const { GraphQLString } = require('graphql');

const type = field.type

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

我是怎么用这个的?我需要在S3对象键前面加上S3根URL,因此我创建了一个指令来执行此操作,它检查并返回条件字符串和数组。还有代码。

代码语言:javascript
复制
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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54674155

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档