【问题标题】:How can I get mapped type names for a graphQL type using type-graphql如何使用 type-graphql 获取 graphQL 类型的映射类型名称
【发布时间】:2019-08-07 12:28:55
【问题描述】:

好的,所以我开始深入研究 graphql,并且我已经使用 koa、type-graphql 和 sequelize-typescript 构建了一个 api。一切都很好......我设法让查询工作,甚至通过使用graphql-fields过滤我在数据库中查询的列来进行一些优化......但是当我给字段名起别名时,我似乎无法获取映射名称.....

例如,给定以下 ObjectType/Sequelize Model....

export interface IDepartment {
    departmentId: number;
    name: string;
    description: string;
}

@ObjectType()
@Table({ underscored: true })
export class Department extends Model<Department> implements IDepartment {
    @Field({ name: 'id' })
    @PrimaryKey
    @Column({ field: 'department_id'})
    public departmentId: number;

    @Field()
    @Length({ max: 100 })
    @Column
    name: string;

    @Field()
    @Length({ max: 100 })
    @AllowNull
    @Column
    description: string;
}

和示例查询....

    query {
    department(name: "Test Dept") {
        id
        name,
        description
    }
}

示例解析器...

async department(@Arg('name') name: string, @Info() info: GraphQLResolveInfo) {
        return Department.findOne({
            where: { name }
        });
    }

这很好用....但是当我这样做时

async department(@Arg('name') name: string, @Info() info: GraphQLResolveInfo) {
    let fields = Object.keys(getFields(info))
    return Department.findOne({
        attributes: fields,
        where: { name }
    });
}

(getFields是graphql-fields),查询失败是因为查询指定了字段名id,就是graphql-fields返回的,但是列名是department_id(sequelize model name departmentId)。

我已经用细齿梳浏览了架构,使用 introspectionFromSchema 函数查看了我的架构的详细副本,但是没有提到部门 ID 或部门 ID.... 但是我知道它在某个地方因为当我从我的 sequelize 查询中排除属性字段时,即使 sequelize 返回 departmentId 作为属性名称,当我从解析器返回它并到达客户端时,属性名称也是 id。

任何帮助将不胜感激....我试图通过仅获取请求的属性而不是整个对象来优化所有内容。我总是可以将映射存储为单独的常量并在我的@Field 定义中使用它们,但我想作为最后的手段这样做,但是如果可以的话,我会尽量保持代码精简......

提前谢谢大家。

【问题讨论】:

    标签: node.js typescript graphql


    【解决方案1】:

    不幸的是,引入name 选项主要是为了支持解析器继承。使用它来映射架构字段名称是一种未记录的功能,因此它不提供任何映射或公开映射元数据。

    对输入或参数类型使用name 选项会更糟 - 这将导致无法访问字段并且属性未定义。

    目前我的建议是保持简单,在适当的修复到来之前不要映射字段名称。

    【讨论】:

      猜你喜欢
      • 2020-03-07
      • 1970-01-01
      • 2018-08-05
      • 2021-01-09
      • 2020-05-29
      • 2021-11-16
      • 2018-10-23
      • 2020-12-19
      • 2016-08-27
      相关资源
      最近更新 更多