Skip to content

Commit

Permalink
add readme
Browse files Browse the repository at this point in the history
  • Loading branch information
adikari committed Nov 16, 2019
1 parent a0b4544 commit fc942bb
Show file tree
Hide file tree
Showing 8 changed files with 351 additions and 1,638 deletions.
3 changes: 0 additions & 3 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ extends:
- prettier
- plugin:import/errors
- plugin:import/warnings
- plugin:jest/recommended
- plugin:react/recommended

globals:
Expand All @@ -26,11 +25,9 @@ settings:
version: "detect"

plugins:
- jest
- prettier

rules: {
"jest/expect-expect": "off",
"no-console": "off",
"prettier/prettier": "error"
}
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
- run: npm install -g yarn
- run: yarn install --pure-lockfile
- run: yarn lint
- run: yarn test
- run: yarn test --coverage
- run: yarn build


2 changes: 1 addition & 1 deletion .github/workflows/npmpublish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
- run: npm install -g yarn
- run: yarn install --pure-lockfile
- run: yarn lint
- run: yarn test
- run: yarn test --coverage
- run: yarn build

publish-npm:
Expand Down
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
171 changes: 169 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,169 @@
# nextjs-with-apollo
Apollo hook to work with NextJS
[![NPM Status][npm-image]][npm-url]
[![GitHub license][license-image]][license-url]
[![LGTM Status][lgtm-image]][lgtm-url]

# ⚓ nextjs-with-apollo
Apollo HOC for NextJS.


## Install

Install the package with npm

```sh
npm install nextjs-with-apollo
```

or with yarn

```sh
yarn add nextjs-with-apollo
```

## Basic Usage

1. Create a HOC

Create the HOC using a basic setup.

```js
// hocs/withApollo.js
import withApollo from 'nextjs-with-apollo';
import ApolloClient from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';

const GRAPHQL_URL = 'https://your-graphql-url';

const createApolloClient = ({ initialState, headers }) =>
new ApolloClient({
uri: GRAPHQL_URL,
cache: new InMemoryCache().restore(initialState || {}) // hydrate cache
});

export default withApollo(createApolloClient);
```
Parameters `initialState` and `headers` are received in the hoc.

If the render is happening in server, all headers received by the server can be accessed via `headers`.
If the render is happening in browser, we hydrate the client cache with the initial stated created in server.

1. Now use the HOC

```js
import React from 'react';
import { useQuery } from '@apollo/react-hooks';

import withApollo from 'hocs/withApollo';

const QUERY = gql`
query Profile {
profile {
name
displayname
}
}
`;

const ProfilePage = () => {
const { loading, error, data } = useQuery(PROFILE_QUERY);

if (loading) {
return <p>loading..</p>;
}

if (error) {
return JSON.stringify(error);
}

return (
<>
<p>user name: {data.profile.displayname}</p>
<p>name: {data.profile.name}</p>
</>
);
};

export default withApollo(ProfilePage);

```

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.

If you dont want to SSR the above page then you can pass `{ssr: false}` to the hoc.

```
export default withApollo(ProfilePage, { ssr: false });
```

If you want, you can also access instance of `apolloClient` in `getInitialProps`.

```js
ProfilePage.getInitialProps = ctx => {
const apolloClient = ctx.apolloClient;
};
```

## SSR with auth

Often graphQL server requires `AuthorizationToken` for authorizing requests. We can use the headers received in server to parse token from client side cookies.

```js
// hocs/withApollo.js
import withApollo from 'nextjs-with-apollo';
import fetch from 'isomorphic-unfetch';
import { InMemoryCache } from 'apollo-cache-inmemory';
import ApolloClient from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { ApolloLink } from 'apollo-link';
import { setContext } from 'apollo-link-context';
import cookie from 'cookie';
import get from 'lodash/get';

const isServer = typeof window === 'undefined';

const getToken = headers => {
const COOKIE_NAME = 'your_auth_cookie_name'
const cookies = isServer ? get(headers, 'cookie', '') : document.cookie;

return get(cookie.parse(cookies), COOKIE_NAME, '');
};

const attachAuth = headers => () => {
const token = getToken(headers);

return {
headers: {
authorization: `Bearer ${token}`
}
};
};

const createApolloClient = ({ initialState, headers = {} }) => {
const authLink = () => setContext(attachAuth(headers));

const httpLink = new HttpLink({
credentials: 'include',
uri: GRAPHQL_ENDPOINT,
fetch
});

return new ApolloClient({
ssrMode: isServer,
link: ApolloLink.from([authLink(), httpLink]),
cache: new InMemoryCache().restore(initialState || {})
});
};

export default withApollo(createApolloClient);
```

## License
Feel free to use the code, it's released using the MIT license.

[npm-image]:https://img.shields.io/npm/v/nextjs-with-apollo.svg
[npm-url]:https://www.npmjs.com/package/nextjs-with-apollo
[license-image]:https://img.shields.io/github/license/adikari/nextjs-with-apollo.svg
[license-url]:https://github.com/adikari/nextjs-with-apollo/blob/master/LICENSE

[lgtm-image]:https://img.shields.io/lgtm/grade/javascript/g/adikari/nextjs-with-apollo.svg?logo=lgtm&logoWidth=18
[lgtm-url]:https://lgtm.com/projects/g/adikari/nextjs-with-apollo/context:javascript
25 changes: 5 additions & 20 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "nextjs-with-apollo",
"version": "0.0.1",
"repository": "https://github.com/ACloudGuru/nextjs-with-apollo",
"version": "1.0.0",
"repository": "https://github.com/adikari/nextjs-with-apollo",
"author": "Subash Adhikari <[email protected]>",
"license": "MIT",
"main": "./lib",
Expand All @@ -10,7 +10,7 @@
],
"scripts": {
"lint": "eslint src",
"test": "jest --coverage",
"test": "echo todo",
"build": "babel ./src --out-dir ./lib",
"watch": "yarn build --watch"
},
Expand All @@ -19,6 +19,8 @@
"@babel/core": "^7.7.2",
"@babel/preset-env": "^7.7.1",
"@babel/preset-react": "^7.7.0",
"@testing-library/react": "^9.3.2",
"apollo-cache-inmemory": "^1.6.3",
"apollo-client": "^2.6.4",
"babel-eslint": "^10.0.3",
"eslint": "^6.6.0",
Expand All @@ -30,7 +32,6 @@
"eslint-plugin-prettier": "^3.1.1",
"eslint-plugin-react": "^7.16.0",
"graphql": "^14.5.8",
"jest": "^24.9.0",
"next": "^9.1.3",
"prettier": "^1.19.1",
"react": "^16.12.0",
Expand All @@ -45,21 +46,5 @@
"dependencies": {
"@apollo/react-hooks": "^3.1.3",
"@apollo/react-ssr": "^3.1.3"
},
"jest": {
"testMatch": [
"**/?(*.)+(spec|test).js?(x)"
],
"testPathIgnorePatterns": [
"/node_modules/"
],
"coverageThreshold": {
"global": {
"branches": 90,
"functions": 90,
"lines": 90,
"statements": 90
}
}
}
}
5 changes: 0 additions & 5 deletions src/withApolloClient.test.js

This file was deleted.

Loading

0 comments on commit fc942bb

Please sign in to comment.