是否可以使用Apollo Server在服务器端本地执行变异或查询 [英] Is it possible to execute a mutation or query locally at server side with Apollo Server
问题描述
我想知道是否可以使用Apollo Server在服务器端本地执行变异或查询.
I would like to know if it is possible to execute a mutation or query locally at server side with Apollo Server.
示例:
1-达到端点GET/createNew
1- Endpoint GET /createNew is reached
2-我运行了一个我定义的突变:
2- I run a mutation I defined like:
apolloserver.mutation(mutation_query).then((response)=>{res.status(200)})
3-将新条目添加到数据库中,并向客户端返回JSON字符串
3- A new entry is added to the database and a JSON string is returned to client
是否存在类似的东西? apolloserver
对象在运行时可用吗?
Does something like that exist? Is a apolloserver
object available at runtime?
我正在使用NodeJS + Express
I'm using NodeJS + Express
推荐答案
我可以正常使用
首先我们启动对象:
import express from 'express';
import { graphql } from 'graphql';
const context = require('./context'); //this is the object to be passed to each resolver function
const schema = require('./schema'); //this is the object returned by makeExecutableSchema({typeDefs, resolvers})
const app = express();
然后,例如,如果要在端点 GET/execute
Then, if we want, for example, to run a query on endpoint GET /execute
app.get('/execute', function(req, res){
var query = `
query myQueryTitle{
queryName{
_id,
...
}
}
`;
graphql(schema, query, null, context)
.then((result) => {
res.json(result.data.queryName);
});
})
因此,每当我们要运行查询或突变时,我们都会调用 graphql
并传递 schema
, requestString
/ query
和 context
对象
So anytime we want to run a query or a mutation, we call graphql
passing schema
, the requestString
/query
and the context
object
这可能与 graphqlExpress
这篇关于是否可以使用Apollo Server在服务器端本地执行变异或查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!