[英]Return custom object to GraphQL resolver
I need to provide custom custom Object as ouput for GraphQL resolver.我需要提供自定义 Object 作为 GraphQL 解析器的输出。
This is for Node-Express backend server with GraphQL setup.这适用于具有 GraphQL 设置的 Node-Express 后端服务器。 I tried sequelized, but I'm testing a new approach, where i need to pass an object as output to graphQL.
我尝试了续集,但我正在测试一种新方法,我需要将 object 作为 output 传递给 graphQL。
const RootQueryType = new GraphQLObjectType({
name: "Query",
fields: {
Sample: {
type: SampleType,
args: {
sampleID: { type: GraphQLID }
},
resolve: async (parent, args) => {
try {
const result = await sql.connect(config).then(pool =>
pool
.request()
.input("sampleID", sql.Int, args.sampleID)
.query(
"SELECT * FROM samples WHERE sampleID = @sampleID"
)
);
const ASB = await result.recordsets[0];
console.log(ASB);
sql.close();
return ASB;
} catch (err) {
console.log(err);
sql.close();
return;
}
}
}
}
});
the result of the query output is查询 output 的结果是
[
{
sampleID: 1,
sampleText: 'sample1'
},
{
sampleID: 2,
sampleText: 'sample2'
}
]
When i return plain object ie ASB[0]当我返回普通 object 即 ASB[0]
{
sampleID: 1,
sampleText: 'sample1'
}
I am getting output in GraphQL but when the entire ASB object is returned, I'm not able to get ouput.我在 GraphQL 中得到 output 但是当返回整个 ASB object 时,我无法获得输出。
The problem is you're declaring the type as single item SampleType
but returning the array of SampleType
问题是您将类型声明为单项
SampleType
但返回SampleType
数组
you can fix it be changing SampleType
to new GraphQLList(SampleType)
您可以通过将
SampleType
更改为new GraphQLList(SampleType)
来修复它
const RootQueryType = new GraphQLObjectType({
name: "Query",
fields: {
Sample: {
type: new GraphQLList(SampleType), // THIS LINE !!!
args: {
sampleID: { type: GraphQLID }
},
resolve: async (parent, args) => {
try {
const result = await sql.connect(config).then(pool =>
pool
.request()
.input("sampleID", sql.Int, args.sampleID)
.query(
"SELECT * FROM samples WHERE sampleID = @sampleID"
)
);
const ASB = await result.recordsets[0];
console.log(ASB);
sql.close();
return ASB;
} catch (err) {
console.log(err);
sql.close();
return;
}
}
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.