Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Auth API #4

Merged
merged 28 commits into from
Jul 14, 2020
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
b816969
Create Auth API
orzechdev May 29, 2020
794ea8e
Update graphql types
orzechdev May 29, 2020
3b0d38e
Fix graphql types
orzechdev Jun 1, 2020
9a2d385
Await password credential api
orzechdev Jun 1, 2020
ef3ab97
Handle no credential api exception
orzechdev Jun 1, 2020
008a8d9
Initialize apollo client in saleor provider
orzechdev Jun 3, 2020
c526aa3
Add apollo provider in saleor provider
orzechdev Jun 3, 2020
b992932
Update readme
orzechdev Jun 3, 2020
bc1e11f
Update readme
orzechdev Jun 4, 2020
991f06f
update readme
orzechdev Jun 5, 2020
f0fc968
Merge branch 'master' into refactor/user-auth
orzechdev Jul 6, 2020
4caaedd
Update credential management api types
orzechdev Jul 6, 2020
c54a8f8
Update readme
orzechdev Jul 6, 2020
206ed13
Update SaleorProvider
orzechdev Jul 6, 2020
d8b4ca6
Change CustomConfig to ConfigInput
orzechdev Jul 6, 2020
1a14f8a
Implement custom apollo configuration for saleor provider
orzechdev Jul 6, 2020
cab8463
Refactor Apollo client initialization
orzechdev Jul 7, 2020
d7c71a4
Update tests
orzechdev Jul 7, 2020
450de9b
Fix LocalStorageHandler reference error
orzechdev Jul 7, 2020
f9b6858
Merge branch 'master' into refactor/user-auth
orzechdev Jul 7, 2020
38550ed
Fix imports
orzechdev Jul 7, 2020
b062967
Update sdk config docs strings
orzechdev Jul 9, 2020
195698a
No cache sign in user
orzechdev Jul 9, 2020
7c9e331
Remove user details from tokenAuth and verifyToken mutations
orzechdev Jul 9, 2020
8d4241e
Load checkout conditionally on sign in
orzechdev Jul 9, 2020
c972e78
Remove FunctionErrorAuthTypes
orzechdev Jul 9, 2020
d75a6cd
Update useHook
orzechdev Jul 9, 2020
8698c0a
Update readme
orzechdev Jul 10, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
162 changes: 115 additions & 47 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,86 +1,154 @@
# Saleor API SDK
<div align="center">
<h1>Saleor SDK</h1>
</div>

This package contains all queries and mutations that are used in our sample storefront.
Still under heavy development.
This package contains methods providing Saleor business logic for storefront. It handles Saleor GraphQL queries and mutations, manages Apollo cache and provides internal state to manage popular storefront use cases, like user authentication or checkout process.

## Setup

```
npm install @saleor/sdk
```
Please take a look at [sample storefront](https://github.com/mirumee/saleor-storefront) which already uses Saleor SDK. For specific use cases you may also refer to [saleor-sdk/examples](https://github.com/mirumee/saleor-sdk/tree/add/examples/examples/react/typescript/src).

Create new saleor client by using our built-in pre-configured apollo client:
> :warning: **Note: Saleor SDK is still under heavy development and its API may change.**

```
import { createSaleorClient } from '@saleor/sdk'
## Table of Contents

const client = createSaleorClient(API_URL)
```
- [Setup](#setup)
- [Features](#features)
- [Local development](#local-development)

## Usage
## Setup

### React
There are two ways to use SDK - making custom implementation or using React components and hooks, which already has that implementation ready.

We provide a custom hook per each query that have near identical API to `react-apollo` but are dynamically typed, with built-in error handling.
### Using React

In your root file:
First install SDK as dependency to your project

```bash
npm install @saleor/sdk
```
import { SaleorProvider } from '@saleor/sdk'
import { client } from './saleor'

import App from './App'
Use `SaleorProvider` with passed custom config in a prop. Then use React hooks in any component passed as child to `SaleorProvider`.

const rootElement = document.getElementById('root')
```tsx
import { SaleorProvider, useAuth } from "@saleor/sdk";

const CUSTOM_CONFIG = { apiUrl: "http://localhost:8000/graphql/" };

const rootElement = document.getElementById("root");
ReactDOM.render(
<SaleorProvider client={client}>
<SaleorProvider config={CUSTOM_CONFIG}>
<App />
</SaleorProvider>,
rootElement
)
);

const App = () => {
const { authenticated, user, signIn } = useAuth();

const handleSignIn = async () => {
const { data, dataError } = await signIn("admin@example.com", "admin");

if (dataError) {
/**
* Unable to sign in.
**/
} else if (data) {
/**
* User signed in succesfully.
**/
}
};

if (authenticated && user) {
return <span>Signed in as {user.firstName}</span>;
} else {
return <button onClick={handleSignIn}>Sign in</button>;
}
};
```

There are 2 types of api calls - queries and mutations.

Query (gets data):
### Custom implementation

```
const { data: TData["data"], loading: boolean, error: ApolloError } = useProductDetails(variables, options?)
```bash
npm install @saleor/sdk
```

Mutation (sets data):
Create new saleor client by using our built-in pre-configured Apollo links and cache:

```
const [
signIn: (options?) => Promise<TData>,
{ data: TData["data"], loading: boolean, error: ApolloError, called: boolean }
] = useSignIn(options?)
```
```tsx
import { createSaleorClient } from "@saleor/sdk";
import { invalidTokenLinkWithTokenHandler, authLink } from "@saleor/sdk/auth";
import { cache } from "@saleor/sdk/cache";

For `options` and full api reference, navigate to [official docs](https://www.apollographql.com/docs/)
const CUSTOM_CONFIG = { apiUrl: "http://localhost:8000/graphql/" };

### Other frameworks
const invalidTokenLink = invalidTokenLinkWithTokenHandler(() => {
/* Handle token expiration case */
});

Create new SaleorAPI instance and use methods available on it
await persistCache({
cache,
storage: window.localStorage,
});

const client = createSaleorClient(
CUSTOM_CONFIG.apiUrl,
invalidTokenLink,
authLink,
cache
);
```
import { SaleorAPI } from 'saleor-sdk'
import { client } from './saleor'

export const saleorAPI = new SaleorAPI(client)
```
Then use SaleorManager to get `SaleorAPI` from `connect` method. This method takes function as an argument, which will be executed every time the `SaleorAPI` state changes.

```tsx
const manager = new SaleorManager(client, config);

let saleorAPI;

manager.connect((referenceToSaleorAPI) => {
if (saleorAPI === undefined) {
saleorAPI = referenceToSaleorAPI;
}
});
```
const { data } = await saleorAPI.getProductDetails(variables, options?)

Finally, methods from `saleorAPI` might be used:

```tsx
const { data, dataError } = await saleorAPI.auth.signIn(
"admin@example.com",
"admin"
);

if (dataError) {
/**
* Unable to sign in.
**/
} else if (data) {
/**
* User signed in succesfully. Read user object from data or from saleorAPI.auth.
**/
const userData = saleorAPI.auth.user;
}
```

### Local development
## Features

We provide an API with methods and fields, performing one, scoped type of work. You may access them straight from `SaleorAPI` or use React hooks, depending on [which setup do you select](#setup).

| API object | React hook | Description |
| :------------------- | :-------------- | :------------------------------------------------------------------------------ |
| `SaleorAPI.auth` | `useAuth()` | Handles user authentication and stores data about the currently signed in user. |
| `SaleorAPI.cart` | `useCart()` | Collects products to cart and calculates their prices. |
| `SaleorAPI.checkout` | `useCheckout()` | Uses cart and handles the whole checkout process. |

## Local development

It is possible to develop storefront and SDK simultaneously. To do this, you need
Our aim it to build SDK, highly configurable, as a separate package, which you will not require modifications. Although if you want to alter the project, escecially if you want to contribute, it is possible to develop storefront and SDK simultaneously. To do this, you need
to link it to the storefront's project.

```language=shell
$ cd build
```bash
$ cd lib
orzechdev marked this conversation as resolved.
Show resolved Hide resolved
$ npm link
$ cd <your storefront path>
$ npm link @saleor/sdk
Expand Down
118 changes: 116 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading