4

假设我有 2 个扩展 RESTDataSource 的 API 类:

class MoviesAPI extends RESTDataSource {
async getMovies() {}
}

class SongsAPI extends RESTDataSource {
async getSongs() {}
}

如何getSongsgetMovies现有的 Apollo 服务器上下文中调用?

4

1 回答 1

5

this.context您可以通过在数据源类中获取 apollo 服务器上下文并dataSources通过this.context.dataSources.

例如

server.ts

import { ApolloServer, gql } from 'apollo-server';
import { MoviesAPI } from './MoviesAPI';
import { SongsAPI } from './SongsAPI';

const typeDefs = gql`
  type Query {
    movies: String
  }
`;
const resolvers = {
  Query: {
    movies: (_, __, { dataSources }) => {
      return dataSources.moviesAPI.getMovies();
    },
  },
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  dataSources: () => {
    return {
      moviesAPI: new MoviesAPI(),
      songsAPI: new SongsAPI(),
    };
  },
});

server.listen().then(({ url }) => {
  console.log(`Apollo server is listening on ${url}`);
});

MoviesAPI.ts

import { RESTDataSource } from 'apollo-datasource-rest';

export class MoviesAPI extends RESTDataSource {
  async getMovies() {
    const songs = await this.context.dataSources.songsAPI.getSongs();
    const movies = ['a', 'b'];
    return JSON.stringify({ movies, songs });
  }
}

SongsAPI.ts

import { RESTDataSource } from 'apollo-datasource-rest';

export class SongsAPI extends RESTDataSource {
  async getSongs() {
    return ['x', 'y'];
  }
}

从客户端发送 GraphQL 查询:

query{
  movies
}

响应负载:

{
  "data": {
    "movies": "{\"movies\":[\"a\",\"b\"],\"songs\":[\"x\",\"y\"]}"
  }
}

包版本:"apollo-datasource-rest": "^0.8.1","apollo-server": "^2.12.0"

源代码:https ://github.com/mrdulin/apollo-graphql-tutorial/tree/master/src/stackoverflow/61425326

于 2020-04-27T03:58:41.423 回答