Apollo Server: как передать токен авторизации в удаленную схему - PullRequest
2 голосов
/ 06 марта 2019

Я создал ApolloServer, который использует удаленную схему. Для удаленной схемы требуется токен авторизации, который я могу получить из запроса на мой сервер apollo. Вот код для сервера Apollo. Я могу жестко закодировать токен в функции customFetch, и все это работает, но я хочу передать токен, полученный при вызове, на мой сервер.

import {makeRemoteExecutableSchema, introspectSchema, mergeSchemas} from 'graphql-tools';
import {HttpLink} from 'apollo-link-http';
import {ApolloServer} from 'apollo-server';
import fetch from 'node-fetch';

// create executable schemas from remote GraphQL APIs
const customFetch = (uri, options) => {
  // How do I set the token from my server req??
  options.headers.Authorization =
    'Bearer eyJhbGciOiJIUzI1NiIsI Not A Real Token kf5iOg9SkxDBVtQnLJuz3hXEDA';
  return fetch(uri, options);
};

const createRemoteExecutableSchemas = async () => {
  let schemas = [];
  const link = new HttpLink({
    uri: 'http://remote.graphql.server:5555/graphql',
    fetch: customFetch,
  });
  const remoteSchema = await introspectSchema(link);
  const remoteExecutableSchema = makeRemoteExecutableSchema({
    schema: remoteSchema,
    link,
  });
  schemas.push(remoteExecutableSchema);
  return schemas;
};

const createNewSchema = async () => {
  const schemas = await createRemoteExecutableSchemas();
  return mergeSchemas({
    schemas,
  });
};

const runServer = async () => {
  const schema = await createNewSchema();
  const server = new ApolloServer({
    schema
  });
  server.listen().then(({url}) => {
    console.log(`?  Server ready at ${url}`);
  });
};

try {
  runServer();
} catch (err) {
  console.error(err);
}

1 Ответ

2 голосов
/ 08 марта 2019

Я боролся с этим некоторое время один. Попробуйте следующий подход:

const express = require('express');
const { introspectSchema, makeRemoteExecutableSchema, ApolloServer } = require('apollo-server-express');
const { HttpLink } = require('apollo-link-http');
const fetch = require('node-fetch');
const { setContext } = require('apollo-link-context');

async function runServer() {
    const httpLink = new HttpLink({ uri: 'http://remote.graphql.server:5555/graphql', fetch });
    const link = setContext((request, prevContext) => {
        if (prevContext.graphqlContext && prevContext.graphqlContext.headers) {
            return {
                headers: {
                    'Authorization': prevContext.graphqlContext.headers.authorization,
                }
            }
        } else {
            return {}
        }
    }).concat(httpLink);

    const schema = await introspectSchema(link);

    const executableSchema = makeRemoteExecutableSchema({
        schema,
        link,
    });

    const server = new ApolloServer({
        schema: executableSchema,
        context: ({ req }) => ({
            headers: req.headers
          }),
    });

    // middleware
    const app = express();
    server.applyMiddleware({ app });

    app.listen({ port: 4000 }, () =>
        console.log(
            '? Server ready at localhost:4000',
        )
    )
}

runServer();
...