是否可以使用Apollo Server在服务器端本地执行变异或查询

Vic*_*ira 2 node.js express graphql apollo-server

我想知道是否有可能使用Apollo Server在服务器端本地执行变异或查询。

例:

1-达到端点GET / createNew

2-我定义了一个突变,例如:

apolloserver.mutation(mutation_query).then((response)=>{res.status(200)})
Run Code Online (Sandbox Code Playgroud)

3-将新条目添加到数据库,并将JSON字符串返回给客户端

是否存在类似的东西?是一个apolloserver对象在运行时可用?

我正在使用NodeJS + Express

Vic*_*ira 5

我知道了

首先我们启动对象:

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();
Run Code Online (Sandbox Code Playgroud)

然后,例如,如果我们要在端点上运行查询 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);
    });
})
Run Code Online (Sandbox Code Playgroud)

因此,无论何时我们想运行查询或变异,我们都将调用graphqlpass schemarequestString/ querycontext对象

这可能与以下情​​况共存 graphqlExpress

  • 虽然这有效,但它实际上并不是通过 Apollo Server 执行的,而是仅使用 graphql.js 中的 execute 方法。只要您不使用任何 Apollo 中间件(例如 Apollo 引擎),这就没问题,因为在这种情况下它们不会运行。 (2认同)
  • 这个问题有解决方案吗@PetrBela - 我正在研究这样的解决方案 - 我们正在使用 Apolloe Server (2认同)