在我使用 Promises 解决它之前,我一直在处理同样的问题。这是我的架构:
const db = require('../db');
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLInt,
} = require('graphql');
const queryType = new GraphQLObjectType({
name: 'RootQuery',
fields:{
usersCount: {
type: GraphQLInt,
resolve: () => {
return db.getUsers().then((result) =>{
return result.length
});
}
}
}
});
const mySchema = new GraphQLSchema({
query: queryType
});
module.exports = mySchema;
数据库.js
var Promise = require("bluebird");
var r =require('rethinkdb');
const dbConfig = {
host: 'localhost',
port: 28015,
db: 'test'
};
const connect = () => {
return new Promise((resolve, reject) => {
r.connect({
host: dbConfig.host,
port: dbConfig.port
}).then((connection)=>{
resolve(connection);
}).catch((e) =>{
reject(e);
});
})
};
const getUsers = () => {
return new Promise( (resolve, reject ) => {
connect().then( (connection) => {
r.db('test').table('users').run(connection).then((cursor) => {
return cursor.toArray()
}).then( (result) => {
resolve(result);
}).then(() => {
connection.close();
}).catch((err) => {
connection.close();
reject(err);
});
}).catch((error) => {
console.log("Connection error: ", error);
reject(error);
});
});
}
exports.getUsers = getUsers;
我希望这会有所帮助。您可以在此处找到完整的工作示例:https ://github.com/luiscript/graphql-rethinkdb-x