项目作者: habx

项目描述 :
⛓ Apollo link which add an api directive to fetch data from multi endpoints
高级语言: TypeScript
项目地址: git://github.com/habx/apollo-multi-endpoint-link.git
创建时间: 2020-03-05T10:27:59Z
项目社区:https://github.com/habx/apollo-multi-endpoint-link

开源协议:MIT License

下载


CircleCI
@habx/apollo-multi-endpoint-link"">Version
@habx/apollo-multi-endpoint-link"">Size
License

Why ?

We wrote an article about why and how we did this link if you want more details.

Install

  1. npm i @habx/apollo-multi-endpoint-link

Setup

  1. import { createHttpLink } from "apollo-link-http";
  2. new ApolloClient({
  3. link: ApolloLink.from([
  4. new MultiAPILink({
  5. endpoints: {
  6. housings: 'https://housings.api',
  7. projects: 'https://projects.api',
  8. ...
  9. },
  10. createHttpLink: () => createHttpLink(),
  11. }),
  12. ])
  13. })

NB: Since default value of httpSuffix is /graphql, endpoints above will be transformed to https://housings.api/graphql and https://projects.api/graphql.
If you do not have common suffix, you can pass an empty string as httpSuffix to avoid this transformation.

NB 2: Supports apollo-link-rest library

API
  1. new MultiAPILink(config, request);
config
Parameter Description Default Required
endpoints Dictionary of endpoints Yes
defaultEndpoint Default endpoint No
createHttpLink Function to generate http link like apollo-link-http Yes
createWsLink Function to generate wsLink like apollo-link-ws No
wsSuffix Suffix added to endpoint for subscriptions queries /graphql/subscriptions No
httpSuffix Suffix added to endpoint for http queries /graphql No
getContext Callback function called to set custom context like headers No
prefixTypenames Add name argument passed in @api directive to every __typename contained in network data response No

Queries

Query with static api name :

  1. query projectList($params: Params) @api(name: projects) {
  2. projects(params: $params) {
  3. nodes {
  4. id
  5. name
  6. }
  7. }
  8. }
  1. const response = useQuery(myQuery);

Query with dynamic api name

  1. query projectList($params: Params) @api(contextKey: "apiName") {
  2. projects(params: $params) {
  3. nodes {
  4. id
  5. name
  6. }
  7. }
  8. }
  1. const response = useQuery(myQuery, { context: { apiName: "projects" } });

Setting custom context

Sometimes you might need to set custom apollo link context like headers for authentication purpose.
This link allows it by doing as following.

  1. new MultiAPILink({
  2. getContext: (endpoint) => {
  3. if (endpoint === 'yourendpoint-with-auth') {
  4. return ({
  5. headers: {
  6. 'Authorization': 'xxxx',
  7. }
  8. })
  9. }
  10. return {}
  11. },
  12. ...
  13. })