|
| 1 | +# graphql-react-client  [](https://github.com/prettier/prettier) |
| 2 | + |
| 3 | +Apollo Client service for React applications |
| 4 | + |
| 5 | +## Installation |
| 6 | + |
| 7 | +`npm i -s graphql-react-client` |
| 8 | +or |
| 9 | +`yarn add graphql-react-client` |
| 10 | + |
| 11 | +## Usage |
| 12 | + |
| 13 | +```typescript |
| 14 | +import React from 'react'; |
| 15 | +import ReactDOM from 'react-dom'; |
| 16 | +import './index.less'; |
| 17 | +import App from './App'; |
| 18 | +import { ApolloClient, ApolloProvider } from '@apollo/client'; |
| 19 | +import { gqlClient } from 'graphql-react-client'; |
| 20 | +import authService from './shared/services/authService'; |
| 21 | + |
| 22 | +gqlClient.init({ |
| 23 | + api: `${process.env.REACT_APP_API}`, |
| 24 | + uri: '/api/', |
| 25 | + publicUri: '/api/public' |
| 26 | +}); |
| 27 | + |
| 28 | +async function initScope(scope) { |
| 29 | + const sessionData: any = await authService.getSessionData(); |
| 30 | + authService.login(sessionData); |
| 31 | + return sessionData?.mainRole === 'TYPE_CUSTOMER' ? 'customer' : scope; |
| 32 | +} |
| 33 | +let scope; |
| 34 | +initScope('privateScope').then(response => { |
| 35 | + scope = response; |
| 36 | +}); |
| 37 | + |
| 38 | +gqlClient.getClient(scope).then(async (client: ApolloClient<any>) => { |
| 39 | + ReactDOM.render( |
| 40 | + <ApolloProvider {...{ client }}> |
| 41 | + <App /> |
| 42 | + </ApolloProvider>, |
| 43 | + document.getElementById('root') |
| 44 | + ); |
| 45 | +}); |
| 46 | + |
| 47 | +``` |
| 48 | +#### and that's it, try it. |
| 49 | + |
| 50 | +## Use in the services. |
| 51 | +```typescript |
| 52 | +import { gqlClient } from 'graphql-react-client'; |
| 53 | + |
| 54 | +const GET = ` |
| 55 | +query ($input: CoreGetInput!){ |
| 56 | + CustomerGet(input: $input){ |
| 57 | + id |
| 58 | + name |
| 59 | + } |
| 60 | +} |
| 61 | +`; |
| 62 | + |
| 63 | +async get(input: any): Promise<CustomerType> { |
| 64 | + const response = await gqlClient.query('myScope', GET, { input }); |
| 65 | +return response.data.CustomerGet; |
| 66 | +} |
| 67 | +``` |
0 commit comments