Skip to content

Commit fc942bb

Browse files
committed
add readme
1 parent a0b4544 commit fc942bb

File tree

8 files changed

+351
-1638
lines changed

8 files changed

+351
-1638
lines changed

.eslintrc.yml

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ extends:
66
- prettier
77
- plugin:import/errors
88
- plugin:import/warnings
9-
- plugin:jest/recommended
109
- plugin:react/recommended
1110

1211
globals:
@@ -26,11 +25,9 @@ settings:
2625
version: "detect"
2726

2827
plugins:
29-
- jest
3028
- prettier
3129

3230
rules: {
33-
"jest/expect-expect": "off",
3431
"no-console": "off",
3532
"prettier/prettier": "error"
3633
}

.github/workflows/build.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ jobs:
1313
- run: npm install -g yarn
1414
- run: yarn install --pure-lockfile
1515
- run: yarn lint
16-
- run: yarn test
16+
- run: yarn test --coverage
1717
- run: yarn build
1818

1919

.github/workflows/npmpublish.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ jobs:
1515
- run: npm install -g yarn
1616
- run: yarn install --pure-lockfile
1717
- run: yarn lint
18-
- run: yarn test
18+
- run: yarn test --coverage
1919
- run: yarn build
2020

2121
publish-npm:

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2018
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.

README.md

Lines changed: 169 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,169 @@
1-
# nextjs-with-apollo
2-
Apollo hook to work with NextJS
1+
[![NPM Status][npm-image]][npm-url]
2+
[![GitHub license][license-image]][license-url]
3+
[![LGTM Status][lgtm-image]][lgtm-url]
4+
5+
# ⚓ nextjs-with-apollo
6+
Apollo HOC for NextJS.
7+
8+
9+
## Install
10+
11+
Install the package with npm
12+
13+
```sh
14+
npm install nextjs-with-apollo
15+
```
16+
17+
or with yarn
18+
19+
```sh
20+
yarn add nextjs-with-apollo
21+
```
22+
23+
## Basic Usage
24+
25+
1. Create a HOC
26+
27+
Create the HOC using a basic setup.
28+
29+
```js
30+
// hocs/withApollo.js
31+
import withApollo from 'nextjs-with-apollo';
32+
import ApolloClient from 'apollo-client';
33+
import { InMemoryCache } from 'apollo-cache-inmemory';
34+
35+
const GRAPHQL_URL = 'https://your-graphql-url';
36+
37+
const createApolloClient = ({ initialState, headers }) =>
38+
new ApolloClient({
39+
uri: GRAPHQL_URL,
40+
cache: new InMemoryCache().restore(initialState || {}) // hydrate cache
41+
});
42+
43+
export default withApollo(createApolloClient);
44+
```
45+
Parameters `initialState` and `headers` are received in the hoc.
46+
47+
If the render is happening in server, all headers received by the server can be accessed via `headers`.
48+
If the render is happening in browser, we hydrate the client cache with the initial stated created in server.
49+
50+
1. Now use the HOC
51+
52+
```js
53+
import React from 'react';
54+
import { useQuery } from '@apollo/react-hooks';
55+
56+
import withApollo from 'hocs/withApollo';
57+
58+
const QUERY = gql`
59+
query Profile {
60+
profile {
61+
name
62+
displayname
63+
}
64+
}
65+
`;
66+
67+
const ProfilePage = () => {
68+
const { loading, error, data } = useQuery(PROFILE_QUERY);
69+
70+
if (loading) {
71+
return <p>loading..</p>;
72+
}
73+
74+
if (error) {
75+
return JSON.stringify(error);
76+
}
77+
78+
return (
79+
<>
80+
<p>user name: {data.profile.displayname}</p>
81+
<p>name: {data.profile.name}</p>
82+
</>
83+
);
84+
};
85+
86+
export default withApollo(ProfilePage);
87+
88+
```
89+
90+
Thats all. Now Profile page will be rendered in the server. You do not need to do anything in `getInitialProps`. All queries are resolved in the sever.
91+
92+
If you dont want to SSR the above page then you can pass `{ssr: false}` to the hoc.
93+
94+
```
95+
export default withApollo(ProfilePage, { ssr: false });
96+
```
97+
98+
If you want, you can also access instance of `apolloClient` in `getInitialProps`.
99+
100+
```js
101+
ProfilePage.getInitialProps = ctx => {
102+
const apolloClient = ctx.apolloClient;
103+
};
104+
```
105+
106+
## SSR with auth
107+
108+
Often graphQL server requires `AuthorizationToken` for authorizing requests. We can use the headers received in server to parse token from client side cookies.
109+
110+
```js
111+
// hocs/withApollo.js
112+
import withApollo from 'nextjs-with-apollo';
113+
import fetch from 'isomorphic-unfetch';
114+
import { InMemoryCache } from 'apollo-cache-inmemory';
115+
import ApolloClient from 'apollo-client';
116+
import { HttpLink } from 'apollo-link-http';
117+
import { ApolloLink } from 'apollo-link';
118+
import { setContext } from 'apollo-link-context';
119+
import cookie from 'cookie';
120+
import get from 'lodash/get';
121+
122+
const isServer = typeof window === 'undefined';
123+
124+
const getToken = headers => {
125+
const COOKIE_NAME = 'your_auth_cookie_name'
126+
const cookies = isServer ? get(headers, 'cookie', '') : document.cookie;
127+
128+
return get(cookie.parse(cookies), COOKIE_NAME, '');
129+
};
130+
131+
const attachAuth = headers => () => {
132+
const token = getToken(headers);
133+
134+
return {
135+
headers: {
136+
authorization: `Bearer ${token}`
137+
}
138+
};
139+
};
140+
141+
const createApolloClient = ({ initialState, headers = {} }) => {
142+
const authLink = () => setContext(attachAuth(headers));
143+
144+
const httpLink = new HttpLink({
145+
credentials: 'include',
146+
uri: GRAPHQL_ENDPOINT,
147+
fetch
148+
});
149+
150+
return new ApolloClient({
151+
ssrMode: isServer,
152+
link: ApolloLink.from([authLink(), httpLink]),
153+
cache: new InMemoryCache().restore(initialState || {})
154+
});
155+
};
156+
157+
export default withApollo(createApolloClient);
158+
```
159+
160+
## License
161+
Feel free to use the code, it's released using the MIT license.
162+
163+
[npm-image]:https://img.shields.io/npm/v/nextjs-with-apollo.svg
164+
[npm-url]:https://www.npmjs.com/package/nextjs-with-apollo
165+
[license-image]:https://img.shields.io/github/license/adikari/nextjs-with-apollo.svg
166+
[license-url]:https://github.com/adikari/nextjs-with-apollo/blob/master/LICENSE
167+
168+
[lgtm-image]:https://img.shields.io/lgtm/grade/javascript/g/adikari/nextjs-with-apollo.svg?logo=lgtm&logoWidth=18
169+
[lgtm-url]:https://lgtm.com/projects/g/adikari/nextjs-with-apollo/context:javascript

package.json

Lines changed: 5 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "nextjs-with-apollo",
3-
"version": "0.0.1",
4-
"repository": "https://github.com/ACloudGuru/nextjs-with-apollo",
3+
"version": "1.0.0",
4+
"repository": "https://github.com/adikari/nextjs-with-apollo",
55
"author": "Subash Adhikari <[email protected]>",
66
"license": "MIT",
77
"main": "./lib",
@@ -10,7 +10,7 @@
1010
],
1111
"scripts": {
1212
"lint": "eslint src",
13-
"test": "jest --coverage",
13+
"test": "echo todo",
1414
"build": "babel ./src --out-dir ./lib",
1515
"watch": "yarn build --watch"
1616
},
@@ -19,6 +19,8 @@
1919
"@babel/core": "^7.7.2",
2020
"@babel/preset-env": "^7.7.1",
2121
"@babel/preset-react": "^7.7.0",
22+
"@testing-library/react": "^9.3.2",
23+
"apollo-cache-inmemory": "^1.6.3",
2224
"apollo-client": "^2.6.4",
2325
"babel-eslint": "^10.0.3",
2426
"eslint": "^6.6.0",
@@ -30,7 +32,6 @@
3032
"eslint-plugin-prettier": "^3.1.1",
3133
"eslint-plugin-react": "^7.16.0",
3234
"graphql": "^14.5.8",
33-
"jest": "^24.9.0",
3435
"next": "^9.1.3",
3536
"prettier": "^1.19.1",
3637
"react": "^16.12.0",
@@ -45,21 +46,5 @@
4546
"dependencies": {
4647
"@apollo/react-hooks": "^3.1.3",
4748
"@apollo/react-ssr": "^3.1.3"
48-
},
49-
"jest": {
50-
"testMatch": [
51-
"**/?(*.)+(spec|test).js?(x)"
52-
],
53-
"testPathIgnorePatterns": [
54-
"/node_modules/"
55-
],
56-
"coverageThreshold": {
57-
"global": {
58-
"branches": 90,
59-
"functions": 90,
60-
"lines": 90,
61-
"statements": 90
62-
}
63-
}
6449
}
6550
}

src/withApolloClient.test.js

Lines changed: 0 additions & 5 deletions
This file was deleted.

0 commit comments

Comments
 (0)