{"_id":"@dfrechette/apollo-datasource-rest","_rev":"4-4e686ff45ccfd7ef8f6baced312c64cb","time":{"0.9.4":"2020-09-27T00:07:58.568Z","created":"2020-09-27T00:11:37.448Z","0.9.5":"2020-09-27T00:11:37.635Z","modified":"2022-04-05T04:17:47.239Z"},"name":"@dfrechette/apollo-datasource-rest","dist-tags":{"latest":"0.9.5"},"versions":{"0.9.5":{"name":"@dfrechette/apollo-datasource-rest","version":"0.9.5","author":{"name":"Apollo","email":"opensource@apollographql.com"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/davidfrechette/apollo-server.git","directory":"packages/apollo-datasource-rest"},"homepage":"https://github.com/davidfrechette/apollo-server#readme","bugs":{"url":"https://github.com/davidfrechette/apollo-server/issues"},"main":"dist/index.js","types":"dist/index.d.ts","engines":{"node":">=6"},"dependencies":{"apollo-datasource":"file:../apollo-datasource","apollo-server-caching":"file:../apollo-server-caching","apollo-server-env":"file:../apollo-server-env","apollo-server-errors":"file:../apollo-server-errors","http-cache-semantics":"^4.0.0"},"devDependencies":{"apollo-server-types":"file:../apollo-server-types"},"description":"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.","_id":"@dfrechette/apollo-datasource-rest@0.9.5","_nodeVersion":"12.14.1","_npmVersion":"6.13.4","dist":{"integrity":"sha512-KwmZHB9Ry2op8p9MabkiRLUonc4Up9yDdzpeYW/dikfcw2jJ40V/EvNT9yLP9YCIi89PFfnhbGkAxIiZzKR+mw==","shasum":"7089127251c2adda9e7d3ae692b57b80b61e31d6","tarball":"https://registry.npmjs.org/@dfrechette/apollo-datasource-rest/-/apollo-datasource-rest-0.9.5.tgz","fileCount":21,"unpackedSize":87223,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfb9i5CRA9TVsSAnZWagAA/9oP/A4K4WiZsZUpqilaq5mu\nR/ycbEUIO/YL9UVeZC2HlrXmTuD3vMc6BI1hIvjrgUw5t27q+alk2p6CJa1u\nranXR1L1maDMItHnzCVJrrljL5VvOqOShEUttVGiMhU59VzfC/N2Hce0GEMM\nAxMTr88r3ZWDvIEc3GhlCnuF4MYGhnK4GRPhbYuTHCOxqu4UkXgHXMBZhXCl\nsbwZB6br208S1OMXeU0XsOJyrmWkeOfddMEQP3smaiJanR1dsTAxoY2kJdJ1\nq6IocYE8LTJB0DpUP9J4XcNWgMOWvO292dxMxrUtIVPp9P4VrNjP2PvFO2TQ\nuW5n4mhaGnceqHxIHD+Sf+Q0B+JJSolVkkZ7JQ/ZR3/nHai12jqMKdNtgpDV\nI2VY92zIru7/RxP1tDjp2Hv08xTi0fOBACHvZ5LbwMrw2ggNOJWY/N0DVMJp\n2kKUkMxqhgP2FPmMtdA0I+uCeKBpp4ukAnqW31lpYoUDwvkzQOzL8r/HmX3p\nK3+X7g1z3XRcOyWV8Ykvihi0fd83D1wrwWIylKTYRlid47JrGWc8Ddb3xeot\n4FRHoFnqh15W0U5xJ5j6ft4JhnHr3xVP/KD++UXpEy5SsWfuyer0kqgFOe0v\niO+X2MciDPXs1RrSIgnK0KvccakTyEHUWb1cKIXPU8ucEbZEcP/01WGYZTdZ\ni7Wq\r\n=bUEN\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIDyW+JVw8g64X01OugyHHDD4rpYQ8wYl4xJaA4HsntGbAiEAvkZz9dJudepXuiLInQgs81AjNU3VGJ1XW+qumCRbET8="}]},"maintainers":[{"name":"dfrechette","email":"david.frechette@cossette.com"}],"_npmUser":{"name":"dfrechette","email":"david.frechette@cossette.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/apollo-datasource-rest_0.9.5_1601165497497_0.3410704857582021"},"_hasShrinkwrap":false}},"maintainers":[{"name":"dfrechette","email":"david.frechette@cossette.com"}],"description":"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.","homepage":"https://github.com/davidfrechette/apollo-server#readme","repository":{"type":"git","url":"git+https://github.com/davidfrechette/apollo-server.git","directory":"packages/apollo-datasource-rest"},"author":{"name":"Apollo","email":"opensource@apollographql.com"},"bugs":{"url":"https://github.com/davidfrechette/apollo-server/issues"},"license":"MIT","readme":"# Apollo REST Data Source\n\nThis 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.\n\n## Documentation\n\nView the [Apollo Server documentation for data sources](https://www.apollographql.com/docs/apollo-server/features/data-sources/) for more details.\n\n## Usage\n\nTo get started, install the `apollo-datasource-rest` package:\n\n```bash\nnpm install apollo-datasource-rest\n```\n\nTo define a data source, extend the [`RESTDataSource`](https://github.com/apollographql/apollo-server/tree/main/packages/apollo-datasource-rest) 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.\n\nYour implementation of these methods can call on convenience methods built into the [RESTDataSource](https://github.com/apollographql/apollo-server/tree/main/packages/apollo-datasource-rest) class to perform HTTP requests, while making it easy to build up query parameters, parse JSON results, and handle errors.\n\n```javascript\nconst { RESTDataSource } = require('apollo-datasource-rest');\n\nclass MoviesAPI extends RESTDataSource {\n  constructor() {\n    super();\n    this.baseURL = 'https://movies-api.example.com/';\n  }\n\n  async getMovie(id) {\n    return this.get(`movies/${id}`);\n  }\n\n  async getMostViewedMovies(limit = 10) {\n    const data = await this.get('movies', {\n      per_page: limit,\n      order_by: 'most_viewed',\n    });\n    return data.results;\n  }\n}\n```\n\n### HTTP Methods\n\nThe `get` method on the [RESTDataSource](https://github.com/apollographql/apollo-server/tree/main/packages/apollo-datasource-rest) makes an HTTP `GET` request. Similarly, there are methods built-in to allow for POST, PUT, PATCH, and DELETE requests.\n\n```javascript\nclass MoviesAPI extends RESTDataSource {\n  constructor() {\n    super();\n    this.baseURL = 'https://movies-api.example.com/';\n  }\n\n  // an example making an HTTP POST request\n  async postMovie(movie) {\n    return this.post(\n      `movies`, // path\n      movie, // request body\n    );\n  }\n\n  // an example making an HTTP PUT request\n  async newMovie(movie) {\n    return this.put(\n      `movies`, // path\n      movie, // request body\n    );\n  }\n\n  // an example making an HTTP PATCH request\n  async updateMovie(movie) {\n    return this.patch(\n      `movies`, // path\n      { id: movie.id, movie }, // request body\n    );\n  }\n\n  // an example making an HTTP DELETE request\n  async deleteMovie(movie) {\n    return this.delete(\n      `movies/${movie.id}`, // path\n    );\n  }\n}\n```\n\nAll 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](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters).\n\n### Intercepting fetches\n\nData 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.\n\nYou can easily set a header on every request:\n\n```javascript\nclass PersonalizationAPI extends RESTDataSource {\n  willSendRequest(request) {\n    request.headers.set('Authorization', this.context.token);\n  }\n}\n```\n\nOr add a query parameter:\n\n```javascript\nclass PersonalizationAPI extends RESTDataSource {\n  willSendRequest(request) {\n    request.params.set('api_key', this.context.token);\n  }\n}\n```\n\nIf you're using TypeScript, make sure to import the `RequestOptions` type:\n\n```javascript\nimport { RESTDataSource, RequestOptions } from 'apollo-datasource-rest';\n\nclass PersonalizationAPI extends RESTDataSource {\n  baseURL = 'https://personalization-api.example.com/';\n\n  willSendRequest(request: RequestOptions) {\n    request.headers.set('Authorization', this.context.token);\n  }\n}\n```\n\n### Resolving URLs dynamically\n\nIn some cases, you'll want to set the URL based on the environment or other contextual values. You can use a getter for this:\n\n```javascript\nget baseURL() {\n  if (this.context.env === 'development') {\n    return 'https://movies-api-dev.example.com/';\n  } else {\n    return 'https://movies-api.example.com/';\n  }\n}\n```\n\nIf you need more customization, including the ability to resolve a URL asynchronously, you can also override `resolveURL`:\n\n```javascript\nasync resolveURL(request: RequestOptions) {\n  if (!this.baseURL) {\n    const addresses = await resolveSrv(request.path.split(\"/\")[1] + \".service.consul\");\n    this.baseURL = addresses[0];\n  }\n  return super.resolveURL(request);\n}\n```\n\n### Accessing data sources from resolvers\n\nTo give resolvers access to data sources, you pass them as options to the `ApolloServer` constructor:\n\n```javascript\nconst server = new ApolloServer({\n  typeDefs,\n  resolvers,\n  dataSources: () => {\n    return {\n      moviesAPI: new MoviesAPI(),\n      personalizationAPI: new PersonalizationAPI(),\n    };\n  },\n  context: () => {\n    return {\n      token: 'foo',\n    };\n  },\n});\n```\n\nApollo 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.)\n\nFrom our resolvers, we can access the data source and return the result:\n\n```javascript\n Query: {\n    movie: async (_source, { id }, { dataSources }) => {\n      return dataSources.moviesAPI.getMovie(id);\n    },\n    mostViewedMovies: async (_source, _args, { dataSources }) => {\n      return dataSources.moviesAPI.getMostViewedMovies();\n    },\n    favorites: async (_source, _args, { dataSources }) => {\n      return dataSources.personalizationAPI.getFavorites();\n    },\n  },\n```\n","readmeFilename":"README.md"}