Apollo服务器、GraphQL和Sequelize-如何将原始数据放入GraphQL模式响应中



在互联网上搜索了一个特定的例子后,我认输了,请求帮助。

我使用Apollo服务器、GraphQL和Sequelize,并调用存储过程,该过程返回从两个不同表创建的记录集。我正在取回数据,但我不知道如何将结果放入GraphQL模式响应中。

这是我的解析器中的代码:

async functionName(_, {input}, {user = null}) {
if (!user) {
throw new AuthenticationError('You must login to use this function');
}
const {record_id} = input;
const result = await DBService.query(
'Call sp_JoinTwoTables_Select(:id)',
{
model: FooModel,
mapToModel: true,
raw: true,
replacements: {id: record_id},
type: QueryTypes.SELECT
}
);
console.log('functionName.result');
console.log(result); // Getting results
return result;
}

这是我的模式中的代码:

const {gql} = require('apollo-server-express');
module.exports = gql`
type Foo {
id: Int!
foo_name: String!
date_created: String!
date_modified: String!
}
extend type Mutation {
functionName(input: fooInput!): fooResponse!
}
input fooInput {
id: Int!
}
type fooResponse {
tree: [fooSchemaForBothTables!]
}
type fooSchemaForBothTables {
id: Int!
foo_name: String!
column_from_second_table: Int!
}
`;

由于数据库中没有表,我创建了一个简单的对象。当失败时,我尝试了一个顺序化的模型对象,但也失败了。这是这个代码:

module.exports = {FooModel: {
id: 0,
fooName: '',
column_from_second_table: 0
}};

我得到的输出是(不是我想的2d数组(:

Executing (default): Call sp_CommunityHierarchy_Select(9)
selectHierarchyTree.result
[
{
'0': {
community_id: 1,
community_name: 'Cars',
level_from_apex: null,
parent_id: null
},
'1': {
community_id: 8,
community_name: 'Chevy',
level_from_apex: 2,
parent_id: 1
},
'2': {
community_id: 9,
community_name: 'Suburban',
level_from_apex: 3,
parent_id: 8
},
meta: [ [ColumnDef], [ColumnDef], [ColumnDef], [ColumnDef] ]
},
{ affectedRows: 6, insertId: 0, warningStatus: 0 }
]

您的原始数据库结果:

  • 是一个数组
  • 第一个元素是一个对象,其记录/项编码为索引命名属性

您所需的突变(为什么不是查询类型!?(响应应该是tree: [fooSchemaForBothTables!]-具有tree命名属性的对象(真的需要额外的嵌套级别?(,并将fooSchemaForBothTables形状的对象数组作为值:

{
tree: [
{
id: 1,
foo_name: 'Cars`,
column_from_second_table: 'whatever`,
},
{
id: 2,
foo_name: 'Chevy`,
column_from_second_table: 'whatever`,
}
]
}

您的工作是将DB响应转换为所需的突变结果形状

提示:您可以在辅助项目(codesandbox(中硬编码此DB结果(一些输入常量(,并编写一些转换fn。准备好后,在此解析器中使用它。

您还可以搜索一些更可靠的sequelize(暂时不要使用graphql(教程,其中包含"更有效"的模型映射。

下一步

如果它是一棵树,那么为什么不将其作为树结构-嵌套的节点/类型返回呢?

最新更新