为了账号安全,请及时绑定邮箱和手机立即绑定

Apollo RESTDataSource 调用其他 RESTDataSource?

Apollo RESTDataSource 调用其他 RESTDataSource?

海绵宝宝撒 2022-07-15 09:36:04
假设我有 2 个扩展 RESTDataSource 的 API 类:class MoviesAPI extends RESTDataSource {async getMovies() {}}class SongsAPI extends RESTDataSource {async getSongs() {}}如何getSongs从getMovies现有的 Apollo 服务器上下文中调用?
查看完整描述

1 回答

?
慕婉清6462132

TA贡献1804条经验 获得超2个赞

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


查看完整回答
反对 回复 2022-07-15
  • 1 回答
  • 0 关注
  • 95 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信