问题描述
我正在使用 graphql-express 创建一个端点,我可以在其中执行 graphql 查询.虽然我将 Sequelize 与 SQL 数据库一起使用,但直接从我的 graphql 之外的服务器使用它感觉不对 resolve代码>功能.如何从定义的同一服务器上查询我的 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
}
}
`)
我将如何创建这个 query
函数?
How would I create this query
function?
推荐答案
GraphQL.js 本身不需要运行 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 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!