Skip to content

Commit

Permalink
Update readme
Browse files Browse the repository at this point in the history
  • Loading branch information
orzechdev committed Jun 5, 2020
1 parent b992932 commit bc1e11f
Show file tree
Hide file tree
Showing 4 changed files with 101 additions and 85 deletions.
150 changes: 85 additions & 65 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,34 @@
<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.

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).

> :warning: **Note: Saleor SDK is still under heavy development and its API may change.**
## Table of Contents

- [Setup](#setup)
- [Usage](#usage)
- [Features](#features)
- [Local development](#local-development)

## Setup

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

### Using React

First install SDK as dependency to your project

```bash
npm install @saleor/sdk
```

In React, all you need to do is to use `SaleorProvider` with passed custom config as a prop. Having that you may use React hooks in any component passed as child to `SaleorProvider`. These hooks are available in the same package.
Use `SaleorProvider` with passed custom config in a prop. Then use React hooks in any component passed as child to `SaleorProvider`.

```tsx
import { SaleorProvider } from "@saleor/sdk";
import App from "./App";
import { SaleorProvider, useAuth } from "@saleor/sdk";

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

Expand All @@ -35,6 +40,30 @@ ReactDOM.render(
</SaleorProvider>,
rootElement
);

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

const handleSignIn = () => {
const { data, dataError } = 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>;
}
};
```

### Custom implementation
Expand All @@ -43,92 +72,83 @@ ReactDOM.render(
npm install @saleor/sdk
```

Create new saleor client by using our built-in pre-configured apollo client:
Create new saleor client by using our built-in pre-configured Apollo links and cache:

```tsx
import { createSaleorClient } from "@saleor/sdk";
import { invalidTokenLinkWithTokenHandler, authLink } from "@saleor/sdk/auth";
import { cache } from "@saleor/sdk/cache";

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

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

await persistCache({
cache,
storage: window.localStorage,
});

const client = createSaleorClient(...);
const client = createSaleorClient(
CUSTOM_CONFIG.apiUrl,
invalidTokenLink,
authLink,
cache
);
```

Then use SaleorManager and get `SaleorAPI` from `connect` method. This method takes function as an argument, which will be executed every time the `SaleorAPI` state changes.
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 saleor;
let saleorAPI;

manager.connect((saleorAPI) => {
if (saleor === undefined) {
saleor = saleorAPI;
manager.connect((referenceToSaleorAPI) => {
if (saleorAPI === undefined) {
saleorAPI = referenceToSaleorAPI;
}
});
```

## Usage

### React hooks

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.

In your root file:
Finally, methods from `saleorAPI` might be used:

```tsx
import { SaleorProvider } from "@saleor/sdk";
import App from "./App";

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

const rootElement = document.getElementById("root");
ReactDOM.render(
<SaleorProvider config={CUSTOM_CONFIG}>
<App />
</SaleorProvider>,
rootElement
const { data, dataError } = await saleorAPI.auth.signIn(
"admin@example.com",
"admin"
);
```

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

Query (gets data):

```tsx
const { data: TData["data"], loading: boolean, error: ApolloError } = useProductDetails(variables, options?)
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;
}
```

Mutation (sets data):
## Features

```tsx
const [
signIn: (options?) => Promise<TData>,
{ data: TData["data"], loading: boolean, error: ApolloError, called: boolean }
] = useSignIn(options?)
```
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).

For `options` and full api reference, navigate to [official docs](https://www.apollographql.com/docs/)
### Other frameworks
Create new SaleorAPI instance and use methods available on it
```tsx
import { SaleorAPI } from "saleor-sdk";
import { client } from "./saleor";

export const saleorAPI = new SaleorAPI(client);
```
```tsx
const { data } = await saleorAPI.getProductDetails(variables, options?)
```
| 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
## 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.

```bash
$ cd build
$ cd lib
$ npm link
$ cd <your storefront path>
$ npm link @saleor/sdk
Expand Down
8 changes: 3 additions & 5 deletions src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,10 @@ interface ResponseError extends ErrorResponse {
// possibly remove callback here and use event emitter
export const invalidTokenLinkWithTokenHandler = (
tokenExpirationCallback: () => void
): {
link: ApolloLink;
} => {
): ApolloLink => {
const link = onError((error: ResponseError) => {
const isTokenExpired = error.graphQLErrors?.some(
error => error.extensions?.exception?.code === "JSONWebTokenExpired"
(error) => error.extensions?.exception?.code === "JSONWebTokenExpired"
);
if (
isTokenExpired ||
Expand All @@ -41,7 +39,7 @@ export const invalidTokenLinkWithTokenHandler = (
tokenExpirationCallback();
}
});
return { link };
return link;
};

export const authLink = setContext((_, context) => {
Expand Down
10 changes: 10 additions & 0 deletions src/cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { InMemoryCache, defaultDataIdFromObject } from "apollo-cache-inmemory";

export const cache = new InMemoryCache({
dataIdFromObject: (obj) => {
if (obj.__typename === "Shop") {
return "shop";
}
return defaultDataIdFromObject(obj);
},
});
18 changes: 3 additions & 15 deletions src/react/components/SaleorProvider/SaleorProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,17 @@
import React, { useEffect, useMemo, useState } from "react";
import { persistCache } from "apollo-cache-persist";
import {
defaultDataIdFromObject,
InMemoryCache,
NormalizedCacheObject,
} from "apollo-cache-inmemory";
import { NormalizedCacheObject } from "apollo-cache-inmemory";
import { ApolloProvider } from "react-apollo";

import { SaleorManager, createSaleorClient } from "../../../";
import { SaleorAPI } from "../../../api";
import { SaleorContext } from "../../context";
import { invalidTokenLinkWithTokenHandler, authLink } from "../../../auth";
import { cache } from "../../../cache";

import { IProps } from "./types";
import { PersistentStorage, PersistedData } from "apollo-cache-persist/types";

const cache = new InMemoryCache({
dataIdFromObject: (obj) => {
if (obj.__typename === "Shop") {
return "shop";
}
return defaultDataIdFromObject(obj);
},
});

export function SaleorProvider({
config,
children,
Expand Down Expand Up @@ -56,7 +44,7 @@ export function SaleorProvider({
*/
const apolloClient = useMemo(() => {
if (cachePersisted) {
const { link: invalidTokenLink } = invalidTokenLinkWithTokenHandler(
const invalidTokenLink = invalidTokenLinkWithTokenHandler(
tokenExpirationCallback
);

Expand Down

0 comments on commit bc1e11f

Please sign in to comment.