├── .nvmrc ├── .node-version ├── src ├── __mocks__ │ └── apollo-client.js ├── index.js ├── withClient.jsx ├── provider.jsx ├── __snapshots__ │ └── provider.test.jsx.snap └── provider.test.jsx ├── .gitattributes ├── .gitignore ├── .eslintignore ├── .editorconfig ├── .babelrc ├── .eslintrc.js ├── LICENSE ├── package.json └── README.md /.nvmrc: -------------------------------------------------------------------------------- 1 | .node-version -------------------------------------------------------------------------------- /.node-version: -------------------------------------------------------------------------------- 1 | 10.14.2 2 | -------------------------------------------------------------------------------- /src/__mocks__/apollo-client.js: -------------------------------------------------------------------------------- 1 | module.exports = {}; 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.lock linguist-generated 2 | *.snap linguist-generated 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | yarn-debug.log* 2 | yarn-error.log* 3 | coverage 4 | node_modules/ 5 | .env 6 | .envrc 7 | .DS_Store 8 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | **/node_modules/* 2 | **/dist/* 3 | **/coverage/* 4 | **/config/* 5 | **/__mocks__/* 6 | **/__snapshots__/* 7 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | export { 2 | default as ApolloMultipleClientsProvider, 3 | ApolloMultipleClientsConsumer, 4 | ApolloMultipleClientContext, 5 | } from './provider'; 6 | export { default as withClient } from './withClient'; 7 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | 7 | charset = utf-8 8 | 9 | indent_style = space 10 | indent_size = 2 11 | 12 | [package.json] 13 | insert_final_newline = false 14 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "react", 4 | "stage-2", 5 | [ 6 | "env", 7 | { 8 | "targets": { 9 | "browsers": ["last 2 version"] 10 | }, 11 | "useBuiltIns": "entry", 12 | "modules": "commonjs" 13 | } 14 | ] 15 | ], 16 | "plugins": ["transform-export-extensions"] 17 | } 18 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | module.exports = { 4 | extends: ['@titelmedia/eslint-config-es6', 'plugin:react/recommended', 'plugin:jest/recommended'], 5 | plugins: ['jest'], 6 | parser: 'babel-eslint', 7 | env: { 8 | browser: true, 9 | node: true, 10 | 'jest/globals': true, 11 | }, 12 | rules: { 13 | 'react/display-name': 'off', // TODO: fix once hs-lint supports react config 14 | }, 15 | overrides: [ 16 | { 17 | files: ['**/*.test.js*', '**/*.spec.js*'], 18 | rules: { 19 | 'react/prop-types': 'off', 20 | }, 21 | }, 22 | ], 23 | settings: { 24 | react: { 25 | version: 'detect' 26 | }, 27 | 'import/resolver': { 28 | 'babel-module': { 29 | extensions: ['.js', '.jsx'], 30 | }, 31 | }, 32 | }, 33 | }; 34 | -------------------------------------------------------------------------------- /src/withClient.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { ApolloProvider, ApolloConsumer } from 'react-apollo'; 3 | 4 | import { ApolloMultipleClientsConsumer } from './provider'; 5 | 6 | export default (clientNamespace, Provider = ApolloProvider, Consumer = ApolloConsumer) => { 7 | if (!clientNamespace) { 8 | throw new Error('Please provide a client namespace'); 9 | } 10 | return WrappedComponent => props => ( 11 | 12 | {context => ( 13 | 14 | {({ getClient }) => { 15 | const client = getClient(clientNamespace); 16 | let result = ; 17 | if (!context || context.client !== client) { 18 | result = {result}; 19 | } 20 | return result; 21 | }} 22 | 23 | )} 24 | 25 | ); 26 | }; 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Titel Media GmbH 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/provider.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import { any, objectOf, node } from 'prop-types'; 3 | 4 | export const ApolloMultipleClientContext = React.createContext({ getClient: () => null }); 5 | 6 | const { Provider, Consumer } = ApolloMultipleClientContext; 7 | 8 | export const ApolloMultipleClientsConsumer = Consumer; 9 | 10 | class ApolloMultipleClientsProvider extends Component { 11 | constructor(props) { 12 | super(props); 13 | 14 | if (!props.clients || !Object.keys(props.clients) === 0) { 15 | throw new Error('You need to define at least one client'); 16 | } 17 | 18 | this.getClient = this.getClient.bind(this); 19 | } 20 | 21 | getClient(name) { 22 | const { clients } = this.props; 23 | const selectedClient = clients[name]; 24 | if (!selectedClient) { 25 | throw new Error(`Could not find client ${name}`); 26 | } 27 | return clients[name]; 28 | } 29 | 30 | render() { 31 | const { children } = this.props; 32 | return {children}; 33 | } 34 | } 35 | 36 | ApolloMultipleClientsProvider.propTypes = { 37 | children: node.isRequired, 38 | clients: objectOf(any), 39 | }; 40 | 41 | ApolloMultipleClientsProvider.defaultProps = { 42 | clients: {}, 43 | }; 44 | 45 | export default ApolloMultipleClientsProvider; 46 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@titelmedia/react-apollo-multiple-clients", 3 | "version": "4.0.5", 4 | "description": "Use Multiple Clients for Your GraphQL Queries with React Apollo Client", 5 | "keywords": [ 6 | "React Apollo", 7 | "GraphQL", 8 | "Apollo Client", 9 | "Multiple Clients" 10 | ], 11 | "homepage": "https://github.com/titel-media/react-apollo-multiple-clients", 12 | "bugs": { 13 | "url": "https://github.com/titel-media/react-apollo-multiple-clients/issues", 14 | "email": "dev@highsnobiety.com" 15 | }, 16 | "repository": "git@github.com:titel-media/react-apollo-multiple-clients.git", 17 | "license": "MIT", 18 | "main": "src/index.js", 19 | "scripts": { 20 | "lint": "eslint --config=.eslintrc.js --ext .jsx,.js .", 21 | "test": "jest --coverage ./src", 22 | "prepare": "install-peers" 23 | }, 24 | "peerDependencies": { 25 | "apollo-client": "^2.4.13", 26 | "graphql": "^14.0.2", 27 | "prop-types": "^15.7.2", 28 | "react": "^16.8.3", 29 | "react-apollo": "^2.5.4", 30 | "react-dom": "^16.8.3" 31 | }, 32 | "devDependencies": { 33 | "@commitlint/cli": "^9.1.2", 34 | "@commitlint/config-conventional": "^9.1.2", 35 | "@titelmedia/eslint-config-es6": "^1.2.4", 36 | "babel-core": "^6.22.0", 37 | "babel-eslint": "^10.0.2", 38 | "babel-jest": "^23.6.0", 39 | "babel-plugin-transform-export-extensions": "^6.22.0", 40 | "babel-preset-env": "^1.7.0", 41 | "babel-preset-react": "^6.22.0", 42 | "babel-preset-stage-2": "^6.22.0", 43 | "eslint": "^6.2.2", 44 | "eslint-plugin-import": "^2.18.2", 45 | "eslint-plugin-jest": "^22.14.1", 46 | "eslint-plugin-react": "^7.14.3", 47 | "husky": "^1.3.1", 48 | "install-peers-cli": "^2.1.1", 49 | "jest": "^23.6.0", 50 | "lint-staged": "^8.2.1", 51 | "react-test-renderer": "^16.8.3" 52 | }, 53 | "commitlint": { 54 | "extends": [ 55 | "@commitlint/config-conventional" 56 | ] 57 | }, 58 | "husky": { 59 | "hooks": { 60 | "pre-commit": "lint-staged", 61 | "commit-msg": "commitlint -E HUSKY_GIT_PARAMS" 62 | } 63 | }, 64 | "lint-staged": { 65 | "*.{js,jsx}": [ 66 | "yarn lint --fix", 67 | "git add" 68 | ] 69 | }, 70 | "resolutions": { 71 | "kind-of": "^6.0.3", 72 | "lodash": "^4.17.19", 73 | "mem": "^4.0.0", 74 | "minimist": "^0.2.1" 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React Apollo Multiple Clients 2 | 3 | ## Motivation and Idea 4 | Inspired by Rafael Nunes (see [Medium Article: Apollo Multiple Clients with React](https://medium.com/open-graphql/apollo-multiple-clients-with-react-b34b571210a5)), we needed a more generic solution. 5 | 6 | ## Install 7 | 8 | ```js 9 | yarn @titelmedia/react-apollo-multiple-clients 10 | ``` 11 | 12 | ## Usage 13 | You can get rid of the original `` and use `` instead. Use the Higher Order Component 'withClient' to set a namespace. 14 | 15 | ```js 16 | import React from 'react'; 17 | import ReactDOM from 'react-dom'; 18 | import ApolloClient from 'apollo-boost'; 19 | import { Query, Mutation } from 'react-apollo'; 20 | 21 | import { ApolloMultipleClientsProvider, withClient } from '@titelmedia/react-apollo-multiple-clients'; 22 | 23 | const client1 = new ApolloClient({ 24 | uri: 'https://graphql.client1.com' 25 | }); 26 | 27 | const client2 = new ApolloClient({ 28 | uri: 'https://graphql.client2.com' 29 | }); 30 | 31 | const clients = { 32 | firstNamespace: client1, 33 | secondNamespace: client2, 34 | }; 35 | 36 | const FETCH_TEST = gql` 37 | query fetch($foo: String!) { 38 | test: post(foo: $foo) { 39 | foo 40 | } 41 | } 42 | `; 43 | 44 | const InnerComponent = ({error, load, data: { test }}) => (loading || error) ? null : test; 45 | 46 | const Component = ({ ...rest }) => ( 47 | 48 | 49 | 50 | 51 | 52 | 53 | ); 54 | 55 | const ClientQueryContainer = withClient('clientName1')(Component); 56 | const ClientQuery1 = withClient('clientName1')(Component); 57 | const ClientQuery2 = withClient('clientName2')(Component); 58 | 59 | const App = () => ( 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | , 68 | ); 69 | 70 | /* Output will be something like 71 | 72 | // context is client1 73 | 74 | 75 | // context is client2 76 | 77 | // context is client1 and is not extra wrapped inside a provider 78 | 79 | 80 | // context is client2 and will be wrapped inside a new container 81 | 82 | 83 | 84 | */ 85 | 86 | ReactDOM.render(, document.getElementById('root')); 87 | ``` -------------------------------------------------------------------------------- /src/__snapshots__/provider.test.jsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`React Apollo Multiple Clients should not override client outside provider 1`] = ` 4 |
5 |
8 |
12 | 13 |
14 |
15 |
16 | `; 17 | 18 | exports[`React Apollo Multiple Clients should override client inside provider 1`] = ` 19 |
20 |
23 |
27 | 28 | clientos 29 | 30 |
31 |
32 |
33 | `; 34 | 35 | exports[`React Apollo Multiple Clients should provide correct client 1`] = ` 36 | Array [ 37 |
40 |
43 | 44 | client1 45 | 46 |
47 |
, 48 |
51 |
54 | 55 | client2 56 | 57 |
58 |
, 59 | ] 60 | `; 61 | 62 | exports[`React Apollo Multiple Clients should provide correct client within nested provider 1`] = ` 63 | Array [ 64 |
67 |
70 | 71 | client1 72 | 73 |
74 |
, 75 |
78 |
81 | 82 | client1 83 | 84 |
87 | 88 | client1 89 | 90 |
91 |
94 |
97 | 98 | client2 99 | 100 |
101 |
102 |
103 |
, 104 |
107 |
110 | 111 | client2 112 | 113 |
114 |
, 115 | ] 116 | `; 117 | 118 | exports[`React Apollo Multiple Clients should throw error when client cannot be found 1`] = `[Error: Could not find client not-available]`; 119 | 120 | exports[`React Apollo Multiple Clients should throw error when client no client is given 1`] = `[Error: Please provide a client namespace]`; 121 | 122 | exports[`React Apollo Multiple Clients should throw error when provider has no clients 1`] = `[Error: You need to define at least one client]`; 123 | 124 | exports[`React Apollo Multiple Clients should work with class as well 1`] = ` 125 |
128 |
129 |
130 | `; 131 | -------------------------------------------------------------------------------- /src/provider.test.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import renderer from 'react-test-renderer'; 3 | import { objectOf, any } from 'prop-types'; 4 | 5 | import { ApolloMultipleClientsProvider, withClient } from '.'; 6 | 7 | const { Provider, Consumer } = React.createContext(); 8 | 9 | const ClientNamePrinter = ({ children, ...rest }) => ( 10 | 11 | {({ client }) => ( 12 |
13 | {client} 14 | {children} 15 |
16 | )} 17 |
18 | ); 19 | 20 | const ProviderWrapper = ({ children, client }) =>
{children}
; 21 | 22 | const client1 = 'client1'; 23 | const client2 = 'client2'; 24 | 25 | const clientList = { 26 | clientName1: client1, 27 | clientName2: client2, 28 | }; 29 | 30 | describe('React Apollo Multiple Clients', () => { 31 | beforeAll(() => { 32 | global.consoleError = console.error; 33 | console.error = () => null; 34 | }); 35 | afterAll(() => { 36 | console.error = global.consoleError; 37 | }); 38 | 39 | it('should throw error when provider has no clients', () => { 40 | try { 41 | renderer.create(); 42 | } catch (err) { 43 | expect(err).toMatchSnapshot(); 44 | } 45 | }); 46 | 47 | it('should throw error when client no client is given', () => { 48 | try { 49 | const Enriched = withClient()(ClientNamePrinter); 50 | renderer.create( 51 | 52 | ); 53 | } catch (err) { 54 | expect(err).toMatchSnapshot(); 55 | } 56 | }); 57 | 58 | it('should throw error when client cannot be found', () => { 59 | try { 60 | const Enriched = withClient('not-available', ProviderWrapper, Consumer)(ClientNamePrinter); 61 | renderer.create( 62 | 63 | ); 64 | } catch (err) { 65 | expect(err).toMatchSnapshot(); 66 | } 67 | }); 68 | 69 | it('should provide correct client', () => { 70 | const ClientQuery1 = withClient('clientName1', ProviderWrapper, Consumer)(ClientNamePrinter); 71 | const ClientQuery2 = withClient('clientName2', ProviderWrapper, Consumer)(ClientNamePrinter); 72 | 73 | const app = renderer.create( 74 | 75 | 76 | ); 77 | 78 | expect(app.toJSON()).toMatchSnapshot(); 79 | }); 80 | 81 | it('should provide correct client within nested provider', () => { 82 | const ClientQueryContainer = withClient('clientName1', ProviderWrapper, Consumer)(ClientNamePrinter); 83 | const ClientQuery1 = withClient('clientName1', ProviderWrapper, Consumer)(ClientNamePrinter); 84 | const ClientQuery2 = withClient('clientName2', ProviderWrapper, Consumer)(ClientNamePrinter); 85 | 86 | const app = renderer.create( 87 | 88 | 89 | 90 | 91 | 92 | 93 | ); 94 | 95 | expect(app.toJSON()).toMatchSnapshot(); 96 | }); 97 | 98 | it('should not override client outside provider', () => { 99 | const Enriched = withClient('test', ProviderWrapper, Consumer)(ClientNamePrinter); 100 | 101 | const app = renderer.create(
102 | 103 |
); 104 | 105 | expect(app.toJSON()).toMatchSnapshot(); 106 | }); 107 | 108 | it('should override client inside provider', () => { 109 | const Enriched = withClient('test', ProviderWrapper, Consumer)(ClientNamePrinter); 110 | 111 | const app = renderer.create(
112 | 113 | 114 | 115 |
); 116 | 117 | expect(app.toJSON()).toMatchSnapshot(); 118 | }); 119 | 120 | it('should work with class as well', () => { 121 | class Foo extends Component { 122 | constructor(props) { 123 | super(props); 124 | this.state = {}; 125 | } 126 | 127 | render() { 128 | const { client } = this.props; 129 | return
{client}
; 130 | } 131 | } 132 | Foo.propTypes = { 133 | client: objectOf(any).isRequired, 134 | }; 135 | 136 | const Enriched = withClient('test', ProviderWrapper, Consumer)(Foo); 137 | 138 | const app = renderer.create( 139 | 140 | ); 141 | 142 | expect(app.toJSON()).toMatchSnapshot(); 143 | }); 144 | }); 145 | --------------------------------------------------------------------------------