1 回答
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
添加回答
举报