问题描述
我正在使用graphql-express创建一个端点,我可以在其中执行graphql查询。虽然我使用Sequelize与SQL数据库,但是直接从我的graphql 之外的服务器使用它是错误的解决
函数。如何从与其定义的服务器相同的服务器中查询我的graphql API?
I am using graphql-express to create an endpoint where I can execute graphql queries in. Although I am using Sequelize with a SQL database it feels wrong to use it directly from the server outside of my graphql resolve
functions. How do I go about querying my graphql API from the same server as it was defined in?
这是我设置graphql端点的方式:
This is how I set up my graphql endpoint:
const express = require('express');
const router = express.Router();
const graphqlHTTP = require('express-graphql');
const gqlOptions = {
schema: require('./schema')
};
router.use('/', graphqlHTTP(gqlOptions));
modules.exports = router;
基本上我想要的是能够做这样的事情:
Basically what I want is to be able to do something like this:
query(`
{
user(id: ${id}) {
name
}
}
`)
如何创建此查询
功能?
推荐答案
本身不需要运行http服务器。 express-graphql只是将查询解析器挂载到http端点的帮助器。
GraphQL.js itself does not require a http server to run. express-graphql is just a helper to mount the query resolver to a http endpoint.
您可以将架构和查询传递给 graphql
,它将返回一个Promise,它将解析查询数据。
You can pass your schema and the query to graphql
, it'll return a Promise that'll resolve the query to the data.
graphql(schema, query).then(result => {
console.log(result);
});
所以:
const {graphql} = require('graphql');
const schema = require('./schema');
function query (str) {
return graphql(schema, str);
}
query(`
{
user(id: ${id}) {
name
}
}
`).then(data => {
console.log(data);
})
这篇关于如何从服务器执行GraphQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!