Optimized HTTP Data Source for Apollo Server
- JSON by default
- 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
- Request Deduplication and a Resource Cache
- Support AbortController to manually cancel all running requests
- Support for Apollo Cache Storage backend
View the Apollo Server documentation for data sources for more details.
To get started, install the apollo-datasource-http
package:
npm install apollo-datasource-http
To define a data source, extend the HTTPDataSource
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 HTTPDataSource class to perform HTTP requests, while making it easy to pass different options and handle errors.
import { HTTPDataSource } from "apollo-datasource-http";
const datasource = new (class MoviesAPI extends HTTPDataSource {
constructor() {
// global client options
super({
requestOptions: {
timeout: 2000,
http2: true,
headers: {
"X-Client": "client",
},
},
});
this.baseURL = "https://movies-api.example.com";
})
onCacheKeyCalculation() {}
// lifecycle hooks for logging, tracing and request, response manipulation
async onRequestError() {}
async beforeRequest() {}
async onResponse() {}
async getMovie(id) {
return this.get(`/movies/${id}`, {
headers: {
"X-Foo": "bar",
},
timeout: 3000,
});
}
}
// cancel all running requests e.g when request is closed prematurely
datasource.abort()