apollo-datasource-rest
This package exports a ([`RESTDataSource`](https://github.com/apollographql/apollo-server/tree/main/packages/apollo-datasource-rest)) class which is used for fetching data from a REST API and exposing it via GraphQL within Apollo Server.
Last updated a month ago by apollo-bot .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install apollo-datasource-rest 
SYNC missed versions from official npm registry.

Apollo REST Data Source

This package exports a (RESTDataSource) class which is used for fetching data from a REST API and exposing it via GraphQL within Apollo Server.

Documentation

View the Apollo Server documentation for data sources for more details.

Usage

To get started, install the apollo-datasource-rest package:

npm install apollo-datasource-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 Accessing data sources from resolvers section below.

Your implementation of these methods can call on convenience methods built into the RESTDataSource class to perform HTTP requests, while making it easy to build up query parameters, parse JSON results, and handle errors.

const { RESTDataSource } = require('apollo-datasource-rest');

class MoviesAPI extends RESTDataSource {
  constructor() {
    super();
    this.baseURL = 'https://movies-api.example.com/';
  }

  async getMovie(id) {
    return this.get(`movies/${id}`);
  }

  async getMostViewedMovies(limit = 10) {
    const data = await this.get('movies', {
      per_page: limit,
      order_by: 'most_viewed',
    });
    return data.results;
  }
}

HTTP Methods

The get method on the RESTDataSource makes an HTTP GET request. Similarly, there are methods built-in to allow for POST, PUT, PATCH, and DELETE requests.

class MoviesAPI extends RESTDataSource {
  constructor() {
    super();
    this.baseURL = 'https://movies-api.example.com/';
  }

  // an example making an HTTP POST request
  async postMovie(movie) {
    return this.post(
      `movies`, // path
      movie, // request body
    );
  }

  // an example making an HTTP PUT request
  async newMovie(movie) {
    return this.put(
      `movies`, // path
      movie, // request body
    );
  }

  // an example making an HTTP PATCH request
  async updateMovie(movie) {
    return this.patch(
      `movies`, // path
      { id: movie.id, movie }, // request body
    );
  }

  // an example making an HTTP DELETE request
  async deleteMovie(movie) {
    return this.delete(
      `movies/${movie.id}`, // path
    );
  }
}

All of the HTTP helper functions (get, put, post, patch, and delete) accept a third options parameter, which can be used to set things like headers and referrers. For more info on the options available, see MDN's fetch docs.

Intercepting fetches

Data sources allow you to intercept fetches to set headers, query parameters, or make other changes to the outgoing request. This is most often used for authorization or other common concerns that apply to all requests. Data sources also get access to the GraphQL context, which is a great place to store a user token or other information you need to have available.

You can easily set a header on every request:

class PersonalizationAPI extends RESTDataSource {
  willSendRequest(request) {
    request.headers.set('Authorization', this.context.token);
  }
}

Or add a query parameter:

class PersonalizationAPI extends RESTDataSource {
  willSendRequest(request) {
    request.params.set('api_key', this.context.token);
  }
}

If you're using TypeScript, make sure to import the RequestOptions type:

import { RESTDataSource, RequestOptions } from 'apollo-datasource-rest';

class PersonalizationAPI extends RESTDataSource {
  baseURL = 'https://personalization-api.example.com/';

  willSendRequest(request: RequestOptions) {
    request.headers.set('Authorization', this.context.token);
  }
}

Resolving URLs dynamically

In some cases, you'll want to set the URL based on the environment or other contextual values. You can use a getter for this:

get baseURL() {
  if (this.context.env === 'development') {
    return 'https://movies-api-dev.example.com/';
  } else {
    return 'https://movies-api.example.com/';
  }
}

If you need more customization, including the ability to resolve a URL asynchronously, you can also override resolveURL:

async resolveURL(request: RequestOptions) {
  if (!this.baseURL) {
    const addresses = await resolveSrv(request.path.split("/")[1] + ".service.consul");
    this.baseURL = addresses[0];
  }
  return super.resolveURL(request);
}

Accessing data sources from resolvers

To give resolvers access to data sources, you pass them as options to the ApolloServer constructor:

const server = new ApolloServer({
  typeDefs,
  resolvers,
  dataSources: () => {
    return {
      moviesAPI: new MoviesAPI(),
      personalizationAPI: new PersonalizationAPI(),
    };
  },
  context: () => {
    return {
      token: 'foo',
    };
  },
});

Apollo Server will put the data sources on the context for every request, so you can access them from your resolvers. It will also give your data sources access to the context. (The reason for not having users put data sources on the context directly is because that would lead to a circular dependency.)

From our resolvers, we can access the data source and return the result:

 Query: {
    movie: async (_source, { id }, { dataSources }) => {
      return dataSources.moviesAPI.getMovie(id);
    },
    mostViewedMovies: async (_source, _args, { dataSources }) => {
      return dataSources.moviesAPI.getMostViewedMovies();
    },
    favorites: async (_source, _args, { dataSources }) => {
      return dataSources.personalizationAPI.getFavorites();
    },
  },

Current Tags

  • 0.9.0-alpha.0                                ...           alpha (4 months ago)
  • 0.9.3                                ...           latest (a month ago)
  • 0.9.2-alpha.1                                ...           next (3 months ago)
  • 0.300.0-alpha.2                                ...           next-v3 (3 days ago)

80 Versions

  • 0.300.0-alpha.2                                ...           3 days ago
  • 0.9.3                                ...           a month ago
  • 0.9.2                                ...           2 months ago
  • 0.9.2-alpha.1                                ...           3 months ago
  • 0.9.2-alpha.0                                ...           3 months ago
  • 0.9.1-alpha.0                                ...           3 months ago
  • 0.9.0                                ...           3 months ago
  • 0.9.0-alpha.1                                ...           4 months ago
  • 0.9.0-alpha.0                                ...           4 months ago
  • 0.8.1                                ...           4 months ago
  • 0.8.1-alpha.5                                ...           4 months ago
  • 0.8.1-alpha.4                                ...           4 months ago
  • 0.8.1-alpha.3                                ...           4 months ago
  • 0.8.1-alpha.1                                ...           5 months ago
  • 0.8.0                                ...           5 months ago
  • 0.8.0-alpha.1                                ...           6 months ago
  • 0.7.0                                ...           6 months ago
  • 0.6.11                                ...           7 months ago
  • 0.6.10                                ...           8 months ago
  • 0.6.9                                ...           9 months ago
  • 0.6.8                                ...           9 months ago
  • 0.6.7                                ...           9 months ago
  • 0.6.6                                ...           10 months ago
  • 0.6.5                                ...           10 months ago
  • 0.6.4                                ...           a year ago
  • 0.6.3                                ...           a year ago
  • 0.6.2                                ...           a year ago
  • 0.6.1                                ...           a year ago
  • 0.6.0                                ...           a year ago
  • 0.5.2-alpha.13                                ...           a year ago
  • 0.5.2-alpha.0                                ...           a year ago
  • 0.5.1                                ...           a year ago
  • 0.5.1-alpha.0                                ...           a year ago
  • 0.5.0                                ...           a year ago
  • 0.4.1-alpha.6                                ...           a year ago
  • 0.4.1-alpha.5                                ...           a year ago
  • 0.4.1-alpha.4                                ...           a year ago
  • 0.4.1-alpha.0                                ...           a year ago
  • 0.4.0                                ...           a year ago
  • 0.4.0-rc.0                                ...           a year ago
  • 0.4.0-alpha.3                                ...           a year ago
  • 0.4.0-alpha.2                                ...           a year ago
  • 0.4.0-alpha.1                                ...           a year ago
  • 0.4.0-alpha.0                                ...           a year ago
  • 0.3.2                                ...           a year ago
  • 0.3.1                                ...           a year ago
  • 0.3.1-rc.0                                ...           a year ago
  • 0.3.0                                ...           2 years ago
  • 0.3.0-alpha.3                                ...           2 years ago
  • 0.2.2                                ...           2 years ago
  • 0.3.0-alpha.2                                ...           2 years ago
  • 0.3.0-alpha.1                                ...           2 years ago
  • 0.3.0-alpha.0                                ...           2 years ago
  • 0.2.1                                ...           2 years ago
  • 0.2.0                                ...           2 years ago
  • 0.2.0-alpha.2                                ...           2 years ago
  • 0.2.0-alpha.1                                ...           2 years ago
  • 0.2.0-alpha.0                                ...           2 years ago
  • 0.2.0-register.2195                                ...           2 years ago
  • 0.1.5                                ...           2 years ago
  • 0.1.4                                ...           2 years ago
  • 0.1.3                                ...           2 years ago
  • 0.1.2                                ...           2 years ago
  • 0.1.1                                ...           2 years ago
  • 0.1.0                                ...           2 years ago
  • 0.1.0-rc.12                                ...           2 years ago
  • 0.1.0-rc.11                                ...           2 years ago
  • 0.1.0-rc.10                                ...           2 years ago
  • 0.1.0-rc.9                                ...           2 years ago
  • 2.0.0-rc.8 [deprecated]           ...           2 years ago
  • 2.0.0-rc.7 [deprecated]           ...           2 years ago
  • 2.0.0-canary.1                                ...           2 years ago
  • 2.0.0-canary.0                                ...           2 years ago
  • 2.0.0-rc.6 [deprecated]           ...           2 years ago
  • 2.0.0-rc.5 [deprecated]           ...           2 years ago
  • 2.0.0-rc.4 [deprecated]           ...           2 years ago
  • 2.0.0-rc.3 [deprecated]           ...           2 years ago
  • 2.0.0-rc.2 [deprecated]           ...           2 years ago
  • 2.0.0-rc.1 [deprecated]           ...           2 years ago
  • 2.0.0-rc.0 [deprecated]           ...           2 years ago

Copyright 2014 - 2016 © taobao.org |