阿波罗RESTDataSource调用其他RESTDataSource吗?

时间:2020-04-25 12:04:44

标签: javascript graphql apollo apollo-server restdatasource

说我有2个扩展RESTDataSource的API类:

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

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

如何在现有Apollo服务器上下文中从getSongs调用getMovies

1 个答案:

答案 0 :(得分:3)

您可以通过数据源类中的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