我是GraphQL和Sequelize的新手,但是我已经开发了一个测试,我可以使用Sequalize的函数进行查询并从Graphiql获得结果,但是我有兴趣使用包含多个表的查询来创建更复杂的查询。 / p>
现在,这段代码运行正常:
schema.js
import {
GraphQLObjectType,
GraphQLNonNull,
GraphQLID,
GraphQLInt,
GraphQLString,
GraphQLFloat,
GraphQLList,
GraphQLSchema
} from "graphql";
import { DB } from "../db";
import {DateTime} from "../scalar/dateTime";
import {Player} from "./Player";
import {League} from "./League";
import {Group} from "./Group";
import {Season} from "./Season";
const Query = new GraphQLObjectType({
name: "Query",
description: "This is root query",
fields: () => {
return {
players: {
type: GraphQLList(Player),
args: {
id: {
type: GraphQLID
}
},
resolve(root, args){
return DB.db.models.tbl003_player.findAll({where: args});
}
},
leagues: {
type: GraphQLList(League),
args: {
id: {
type: GraphQLID
}
},
resolve(root, args){
return DB.db.models.tbl001_league.findAll({where: args});
}
},
groups: {
type: GraphQLList(Group),
args: {
id: {
type: GraphQLID
}
},
resolve(root, args){
return DB.db.models.tbl024_group.findAll({where: args});
}
},
seasons: {
type:GraphQLList(Season),
args: {
id: {
type: GraphQLID
}
},
resolve(root, args){
return DB.db.models.tbl015_seasons.findAll({where: args})
}
}
}
}
});
const Schema = new GraphQLSchema({
query: Query
});
module.exports.Schema = Schema;
所以,我想做一个简单的测试,知道如何将原始查询中的数据返回到GraphQL。我已经读过resolve方法返回一个promise,我试图用查询结果返回一个promise,但它不起作用。
players: {
type: GraphQLList(Player),
args: {
id: {
type: GraphQLID
}
},
resolve(root, args){
DB.db.query("select * from tbl003_player where id = 14",
{raw: true, type: DB.db.QueryTypes.SELECT}).then((players)=>{
let myPromise = new Promise((resolve, reject)=>{
resolve(players);
});
return myPromise;
}).catch((reject)=>{
console.log("Error: " + reject);
});
}
},
因此,如何从Sequelize到GraphQL的查询中返回数据?
答案 0 :(得分:3)
返回你从续集中获得的承诺。在承诺之后,你也做了许多不需要的工作。也许在继续之前阅读更多关于承诺的内容:)
resolve(root, args){
return DB.db.query(
"select * from tbl003_player where id = 14",
{ raw: true, type: DB.db.QueryTypes.SELECT }
);
}