【发布时间】: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