Как вызвать запрос / мутацию GraphQL из серверного сервера Express? - PullRequest
0 голосов
/ 06 февраля 2019

Мой внешний интерфейс - localhost:3000, а мой сервер GraphQL - localhost:3333.

Я использовал response-apollo для запроса / изменения в земле JSX, но не сделал запрос / мутацию изЭкспресс еще.

Я хотел бы сделать запрос / мутацию здесь в моем server.js.

server.get('/auth/github/callback', (req, res) => {
  // send GraphQL mutation to add new user
});

Ниже, кажется, правильное направление, но я получаю TypeError: ApolloClient is not a constructor:

const express = require('express');
const next = require('next');
const ApolloClient = require('apollo-boost');
const gql = require('graphql-tag');


// setup
const client = new ApolloClient({
  uri: 'http://localhost:3333/graphql'
});
const app = next({dev});
const handle = app.getRequestHandler();

app
  .prepare()
  .then(() => {
    const server = express();

    server.get('/auth/github/callback', (req, res) => {
      // GraphQL mutation
      client.query({
        query: gql`
          mutation ADD_GITHUB_USER {
            signInUpGithub(
              email: "email@address.com"
              githubAccount: "githubusername"
              githubToken: "89qwrui234nf0"
            ) {
              id
              email
              githubToken
              githubAccount
            }
          }
        `,
      })
        .then(data => console.log(data))
        .catch(error => console.error(error));
    });

    server.listen(3333, err => {
      if (err) throw err;
      console.log(`Ready on http://localhost:3333`);
    });
  })
  .catch(ex => {
    console.error(ex.stack);
    process.exit(1);
  });

В этом посте Аполлон упоминается как решение , но не приводится пример.

Как вызвать мутацию GraphQL с сервера Express :3000 в GraphQL :3333?

Ответы [ 3 ]

0 голосов
/ 08 февраля 2019

Скорее всего, это то, что вы ищете:

const { createApolloFetch } = require('apollo-fetch');

const fetch = createApolloFetch({
 uri: 'https://1jzxrj179.lp.gql.zone/graphql',
});

fetch({
 query: '{ posts { title }}',
}).then(res => {
 console.log(res.data);
});

// You can also easily pass variables for dynamic arguments
fetch({
 query: `query PostsForAuthor($id: Int!) {
  author(id: $id) {
  firstName
   posts {
    title
    votes
   }
  }
 }`,
 variables: { id: 1 },
}).then(res => {
 console.log(res.data);
});

Взято из этого поста, может быть полезно и другим: https://blog.apollographql.com/4-simple-ways-to-call-a-graphql-api-a6807bcdb355

0 голосов
/ 09 февраля 2019

Вы можете использовать graphql-request , это простой клиент GraphQL.

const { request } = require('graphql-request');

request('http://localhost:3333/graphql', `mutation ADD_USER($email: String!, $password: String!) {
  createUser(email: $email, password: $password) {
    id
    email
  }
}`, {email: 'john.doe@mail.com', password: 'Pa$$w0rd'})
.then(data => console.info(data))
.catch(error => console.error(error));

Он также поддерживает CORS.

const { GraphQLClient } = require('graphql-request');

const endpoint = 'http://localhost:3333/graphql';
const client = new GraphQLClient(endpoint, {
  credentials: 'include',
  mode: 'cors'
});

client.request(`mutation ADD_USER($email: String!, $password: String!) {
  createUser(email: $email, password: $password) {
    id
    email
  }
}`, {email: 'john.doe@mail.com', password: 'Pa$$w0rd'})
.then(data => console.info(data))
.catch(error => console.error(error));

Я использую его длясделать тесты E2E.

0 голосов
/ 08 февраля 2019

Когда вы получаете ApolloClient с require вместо import Я думаю, что вам не хватает этой части:

// es5 or Node.js
const Boost = require('apollo-boost');
const ApolloClient = Boost.DefaultClient;

или

const ApolloBoost = require('apollo-boost');
const ApolloClient = ApolloBoost.default;

Попробуйте один из них и посмотрите, работает ли он.

...