apollo-ds-rest
v0.1.0
Published
[![CI](https://github.com/StarpTech/apollo-datasource-rest/actions/workflows/ci.yml/badge.svg)](https://github.com/StarpTech/apollo-datasource-rest/actions/workflows/ci.yml)
Downloads
4
Readme
Apollo REST Data Source
Optimized REST Data Source for Apollo Server
- Optimized for JSON REST
- HTTP/1 Keep-alive agents for socket reuse
- HTTP/2 support (requires Node.js 15.10.0 or newer)
- Uses Got a modern HTTP Client shipped with:
- Retry mechanism
- Request cancellation
- Timeout handling
- RFC 7234 compliant HTTP caching
- LRU Cache with ttl to memoize GET requests within the same graphql request
- AbortController to cancel all running requests
- Support for Apollo Cache Storage backend
Documentation
View the Apollo Server documentation for data sources for more details.
Usage
To get started, install the apollo-ds-rest
package:
npm install apollo-ds-rest
To define a data source, extend the RESTDataSource
class and implement the data fetching methods that your resolvers require. Data sources can then be provided via the dataSources
property to the ApolloServer
constructor, as demonstrated in the section below.
const server = new ApolloServer({
typeDefs,
resolvers,
dataSources: () => {
return {
moviesAPI: new MoviesAPI()
};
},
});
Your implementation of these methods can call on convenience methods built into the RESTDataSource class to perform HTTP requests, while making it easy to pass different options and handle errors.
const { RESTDataSource } = require("apollo-ds-rest");
class MoviesAPI extends RESTDataSource {
constructor() {
// global client options
super({
timeout: 2000,
http2: true,
headers: {
"X-Client": "client",
},
});
this.baseURL = "https://movies-api.example.com";
}
cacheKey() {}
// lifecycle hooks for logging, tracing and request manipulation
didEncounterError() {}
async willSendRequest() {}
async didReceiveResponse() {}
async getMovie(id) {
return this.get(`/movies/${id}`, {
headers: {
"X-Foo": "bar",
},
timeout: 3000,
});
}
}