Git Product home page Git Product logo

saleor-sdk's Introduction

Saleor SDK

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 which already uses Saleor SDK. For specific use cases you may also refer to saleor-sdk/examples.

โš ๏ธ Note: Saleor SDK is still under heavy development and its API may change.

Table of Contents

Setup

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

npm install @saleor/sdk

Use SaleorProvider with passed custom config in a prop. Then use React hooks in any component passed as child to SaleorProvider.

import { SaleorProvider, useAuth } from "@saleor/sdk";

const config = { apiUrl: "http://localhost:8000/graphql/" };
const apolloConfig = {
  /* Optional custom Apollo client config */
};

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

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

  const handleSignIn = async () => {
    const { data, dataError } = await signIn("[email protected]", "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

npm install @saleor/sdk

Create new Saleor cache, Saleor links and Saleor client or use your own cache, Apollo links or even Apollo client:

import {
  createSaleorCache,
  createSaleorClient,
  createSaleorLinks,
} from "@saleor/sdk";

const apiUrl = "http://localhost:8000/graphql/";

const cache = await createSaleorCache({
  persistCache: true,
});

const links = createSaleorLinks({
  apiUrl,
  tokenExpirationCallback: () => {
    /* Handle token expiration case */
  },
});

const client = createSaleorClient(cache, links);

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.

const config = { apiUrl };
const manager = new SaleorManager(client, config);

let saleorAPI;

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

Finally, methods from saleorAPI might be used:

const { data, dataError } = await saleorAPI.auth.signIn(
  "[email protected]",
  "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;
}

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.

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

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.

$ cd lib
$ npm link
$ cd <your storefront path>
$ npm link @saleor/sdk

Notice that in our example storefront webpack is configured to always resolve react to ./node_modules/react. It may seem redundant for the most use cases, but helps in sdk's local development, because it overcomes npm's limitations regarding peer dependencies hoisting, explicitely telling webpack to always have one and only copy of react.

saleor-sdk's People

Contributors

dominik-zeglen avatar orzechdev avatar krzysztofwolski avatar nlkhagva avatar

Stargazers

Roman avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.