• Stars
    star
    129
  • Rank 279,262 (Top 6 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 4 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Deprecated! See the announcement below. JavaScript/TypeScript SDK for building e-commerce experiences and checkouts with Saleor API.

Saleor SDK - DEPRECATED

This package contains methods providing Saleor business logic for a storefront and apps. It handles Saleor GraphQL queries and mutations, manages Apollo cache, and provides an internal state to manage popular storefront use cases, like user authentication.

⚠️ Note: Saleor SDK is DEPRECATED. See the announcement.

For authentication, follow the Saleor docs and use @saleor/auth-sdk.

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 following dependencies to your project

npm install @saleor/sdk @apollo/client graphql

Use SaleorProvider with passed Saleor's client created by createSaleorClient in a prop. Then use React hooks in any component passed as child to SaleorProvider.

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

const client = createSaleorClient({
  apiUrl: "<SALEOR_GRAPHQL_URL>",
  channel: "<CHANNEL>",
});

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

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

  const handleSignIn = async () => {
    const { data } = await login({
      email: "[email protected]",
      password: "admin",
    });

    if (data.tokenCreate.errors.length > 0) {
      /**
       * Unable to sign in.
       **/
    } else if (data) {
      /**
       * User signed in successfully.
       **/
    }
  };

  if (authenticated && user) {
    return <span>Signed in as {user.firstName}</span>;
  }

  return <button onClick={handleSignIn}>Sign in</button>;
};

Using with NodeJS and other frameworks

npm install @saleor/sdk @apollo/client graphql

Then use createSaleorClient to get Saleor api methods and internal config variables like channel and Apollo client.

import { createSaleorClient } from "@saleor/sdk";

const client = createSaleorClient({
  apiUrl: "<SALEOR_GRAPHQL_URL>",
  channel: "<CHANNEL>",
});

const { auth, config, _internal } = client;

Finally, API methods can be used:

const { data } = await auth.login({
  email: "[email protected]",
  password: "admin",
});

if (data.tokenCreate.errors.length > 0) {
  /**
   * Unable to sign in.
   **/
} else if (data) {
  /**
   * User signed in successfully.
   **/
  const userData = api.auth.tokenCreate.user;
}

Custom HTTP communication with SDK authorization

SDK provides fetch method with all the necessary authorization headers assigned to HTTP requests and handled authorization token creation, verification and refresh inside, which you may use instead of built-in browser fetch. Using SDK auth login or logout methods will appropriately alter fetch behavior automatically, like including Authorization Bearer header in HTTP request.

import { createFetch } from "@saleor/sdk";

const authorizedFetch = createFetch();

const result = await authorizedFetch("https://example.com");

If you use GraphQL you may pass SDK fetch to the Apollo client:

const authorizationLink = new HttpLink({
  fetch: authorizedFetch,
});
const apolloClient = new ApolloClient({
  link: authorizationLink,
});

SDK fetch method uses cross-fetch under the hood.

Features

We provide an API with methods and fields, performing one, scoped type of work. You may access them straight from createSaleorClient() or use React hooks:

API object React hook Description
getState() useAuthState() Returns current SDK state: user, authenticated and authenticating.
auth useAuth() Handles user authentication methods.
user useUser() Handles user account methods.
config useSaleorConfig() Handles SDK configuration.

SDK supports OpenId Connect methods provided by Saleor API. They are under auth object and useAuth hook. For more usage details, please check https://docs.saleor.io/docs/3.0/developer/available-plugins/openid-connect.

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, especially 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, explicitly telling webpack to always have one and only copy of react.

Configuration

Set environment variables:

export API_URI=https://your.saleor.instance.com/graphql/
export [email protected]
export TEST_AUTH_PASSWORD=admin

Development

  1. Download repository
  2. Install dependencies: npm i
  3. Now you can start files watcher with: npm run start

Production build

npm run build

Tests

Tests are located at /test directory. To start the test suite:

npm run test

All communication with API is prerecorded using Polly.JS. Unless requests changed or code executes new ones, no requests to API will be made.

Changes in /recordings directory should be reviewed before committing to make sure that changes in communication are intentional.

Code quality

The project has configured Prettier and ESLint. To check your code:

npm run lint

Fetch current GraphQL schema

npm run download-schema

Command will overwrite introspection.json with server schema, based on API_URL variable.

Updating TS types

GraphQL Code Generator is an automatic tool that converts schema to TS types. After changing schema file run:

npm run build-types

Updating recordings

Changes in the core user methods and tests may result in failing tests. Typically you may encounter the following error:

request to http://localhost:8000/graphql/ failed, reason: connect ECONNREFUSED 127.0.0.1:8000

To fix this run npm run test with the following variables:

  • API_URI
  • TEST_AUTH_EMAIL
  • TEST_AUTH_PASSWORD

After the tests run the recordings should be updated. Next time you run tests without variables, tests will use updated recordings.

More Repositories

1

saleor

Saleor Core: the high performance, composable, headless commerce API.
Python
20,676
star
2

storefront

Saleor Storefront built with React 18, Next.js 14, App Router, TypeScript, GraphQL, and Tailwind CSS.
TypeScript
983
star
3

saleor-dashboard

A GraphQL-powered, single-page dashboard application for Saleor.
TypeScript
832
star
4

saleor-storefront

A GraphQL-powered, NextJs-based, PWA storefront for Saleor. IMPORTANT: This project is [DEPRECATED] in favor of saleor/react-storefront soon to become our default demo and storefront starter pack.
TypeScript
768
star
5

saleor-platform

All Saleor services started from a single repository with docker-compose.
640
star
6

saleor-docs

Saleor documentation.
JavaScript
106
star
7

apps

A central space for Saleor Apps, integrations, and the App Store πŸš€
TypeScript
105
star
8

macaw-ui

MacawUI: an official UI design kit for Saleor
TypeScript
100
star
9

cli

Command-line interface allowing interaction with Saleor Cloud environments.
TypeScript
69
star
10

saleor-app-template

Your boilerplate for new Saleor Apps. Batteries included.
TypeScript
62
star
11

app-sdk

SDK for building great Saleor Apps
TypeScript
46
star
12

saleor.io-learn

The Saleor Tutorial content. Learn how to create production-grade Saleor storefronts with React and Next.js. https://saleor.io/learn
39
star
13

saleor-app-payment-adyen

TypeScript
36
star
14

saleor-app-slack

TypeScript
29
star
15

saleor-next-starter

TypeScript
27
star
16

saleor-checkout

Migrated into a monorepo: https://github.com/saleor/react-storefront | The first fully open source and production-ready checkout experience.
TypeScript
22
star
17

saleor-app-klaviyo

TypeScript
20
star
18

auth-sdk

TypeScript
19
star
19

examples

Examples showing how to use the Saleor API.
15
star
20

saleor-app-payment-klarna

TypeScript
15
star
21

saleor-graphql-playground

TypeScript
12
star
22

saleor-app-payment-stripe

TypeScript
12
star
23

app-bridge

An official library for handling all communication between Saleor Dashboard and Saleor Apps.
TypeScript
12
star
24

create-saleor-app

TypeScript
10
star
25

app-examples

Common examples and patterns writing great Saleor apps
10
star
26

example-flutter

Saleor Example: Flutter Mobile App (Dart)
Dart
9
star
27

example-react-native-typescript

Saleor Example: React Native App in TypeScript using Expo
TypeScript
9
star
28

saleor-stellate

Stellate support for Saleor Commerce
TypeScript
9
star
29

saleor-email-templates

Example e-mail templates for Saleor
HTML
9
star
30

dummy-payment-app

Bare-bones app for testing Saleor's Transactions API
TypeScript
8
star
31

example-nextjs-app-router-starter

Saleor Example: Next.js 13 App Router Starter
TypeScript
8
star
32

requests-hardened

A library that overrides the default behaviors of the requests library, and adds new security features.
Python
8
star
33

saleor-app-search

TypeScript
6
star
34

tutorial-walkthrough

TypeScript
6
star
35

saleor-app-cms

TypeScript
6
star
36

example-nextjs-stripe

TypeScript
6
star
37

saleor-plugin-avatax-excise

Python
6
star
38

example-react-cra-typescript

Saleor Example: React App in TypeScript using Create React App (CRA)
TypeScript
5
star
39

saleor-avatax

TypeScript
5
star
40

saleor-app-invoices

Saleor integration for invoices generation
TypeScript
5
star
41

saleor-taxjar

TypeScript
5
star
42

saleor-admin-email-templates

Saleor admin email MJML templates: Reset password, export data, staff order
HTML
4
star
43

graphiql-plugin-collection

TypeScript
4
star
44

devtools-integration-tests

This is a hub for integration and e2e tests for CLI
TypeScript
4
star
45

saleor-app-data-importer

TypeScript
3
star
46

.github

3
star
47

example-react-nextjs-apollo-typescript

Saleor Example: React App in TypeScript with Apollo GraphQL using Next.js
TypeScript
3
star
48

json-schema-compiler

TypeScript
3
star
49

saleor-app-payment-template

Template Saleor payments apps are built from
TypeScript
3
star
50

saleor-app-emails-and-messages

TypeScript
2
star
51

saleor-app-klaviyo-old

TypeScript
2
star
52

digitalocean-1click

Shell
2
star
53

saleor-og

TypeScript
2
star
54

saleor-app-algolia

TypeScript
1
star
55

saleor-app-abandoned-checkouts

Example app built for documentation purposes
TypeScript
1
star
56

app-debug-bar

TypeScript
1
star
57

eslint-plugin-saleor-app

ESLint plugin with rules for Saleor Apps
TypeScript
1
star
58

marketplace-content

Marketplace content
1
star
59

example-auth-nextjs-pages-router

Saleor Example: Auth SDK with Next.js (Pages Router) in TypeScript
TypeScript
1
star
60

shellcheck-gha

Extracts and checks shell scripts in Github Workflows for potential issues using ShellCheck.
Python
1
star