npm package: @krubkrong/sdk-js
Description: Krubkrong SDK for JS
Author: @asurraa
Latest version: 1.2.11

<div align="center">
	<h1>Krubkrong SDK for JavaScript</h1>
</div>

## Installation

```
for npm
npm install @krubkrong/sdk-js

for yarn
yarn add @krubkrong/sdk-js


```

## Usage

Create two React Contexts, One is is for **integration tokens** and API URL and another is for Krubkrong Client.

> First Context is for Token and API URL

```tsx
export interface IUserStoreContext {
  clientStoreToken: string;
  apiRoute?: string;
  apiRouteWithApi: string;
  subdomain?: string;
  customerToken?: string;
  children: React.ReactNode;
}

export const UserClientStoreContext = createContext<IUserStoreContext>(null!);

export const UserClientStoreProvider: FC<IUserStoreContext> = (props) => {
  return (
    <UserClientStoreContext.Provider
      value={{
        customerToken: props.customerToken,
        clientStoreToken: props.clientStoreToken as string,
        apiRouteWithApi: props.apiRoute as string,
        apiRoute: props.apiRouteWithApi,
        subdomain: props.subdomain,
        children: props.children,
      }}
    >
      {props.children}
    </UserClientStoreContext.Provider>
  );
};

export const useStoreClientContext = () => {
  return useContext(UserClientStoreContext);
};
```

> Second Context for Krubkrong Client

```tsx
interface IKrubKrongSDKContext {
  krubkrong: Client;
}

const KrubkrongSDKContext = createContext<IKrubKrongSDKContext>({
  krubkrong: null!,
});

export const useKrubKrongSDKContext = () => useContext(KrubkrongSDKContext);

export const KrubkrongSDKProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const { clientStoreToken, apiRouteWithApi, subdomain, customerToken } =
    useStoreClientContext();

  const krubkrong = new Client({
    auth: clientStoreToken,
    subdomain: subdomain,
    baseUrl: apiRouteWithApi,
    customerToken: customerToken as string,
  });

  return (
    <KrubkrongSDKContext.Provider value={{ krubkrong }}>
      {children}
    </KrubkrongSDKContext.Provider>
  );
};
```

Import and initialize in NextJs Layout Server side page using an **Customer Client Stored in Cookies** and default env declared in a .env file.

```tsx
const clientSubdomain = process.env.CLIENT_SUBDOMAIN;
const apiRouteJson = process.env.NEXT_OPEN_API_ROUTE;
const apiRoute = process.env.API_ROUTE;

const clientToken = process.env.CLIENT_TOKEN?.toString();

const cookieStore = cookies();
const clientEcommerceToken = cookieStore.get("clientToken");

const customerTokenStatus = cookieStore.has("clientToken");

return (
  <html lang="en">
    <ClientOnly>
      <ToasterProvider />
    </ClientOnly>
    <body className={inter.className}>
      <UserClientStoreProvider
        customerToken={clientEcommerceToken?.value as string}
        apiRouteWithApi={apiRouteJson as string}
        clientStoreToken={clientToken as string}
        apiRoute={apiRoute}
        subdomain={clientSubdomain}
      >
        <KrubkrongSDKProvider>{children}</KrubkrongSDKProvider>
      </UserClientStoreProvider>
    </body>
  </html>
);
```

## Example

```tsx
"use client";

import { useKrubKrongSDKContext } from "../../../context/sdk-initial.context";
import { useStoreClientContext } from "../../../context/store-token.context";
import { ResponseAllProductType } from "@krubkrong/sdk-js/types";

const { krubkrong } = useKrubKrongSDKContext();
const [products, setProducts] = useState<ResponseAllProductType>();

useEffect(() => {
  krubkrong.products
    .productList({
      limit: 10,
      page: 1,
    })
    .then((res) => {
      setProducts(res);
    })
    .catch((err) => {
      toast.error("Failed to Find Shop");
    });
}, []);
```

### Client options

The `Client` supports the following options on initialization. These options are all keys in the single constructor parameter.

| Option          | Default value                 | Type         | Description                                                                                                                                                  |
| --------------- | ----------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `auth`          | `undefined`                   | `string`     | Bearer token for Open API authentication. If left undefined, the `auth` parameter should be set on each request.                                             |
| `customerToken` | `undefined`                   | `string`     | Bearer token for Ecommerce authentication. If left undefined, the `customerToken` parameter should be set on each request.                                   |
| `logLevel`      | `LogLevel.WARN`               | `LogLevel`   | Verbosity of logs the instance will produce. By default, logs are written to `stdout`.                                                                       |
| `timeoutMs`     | `60_000`                      | `number`     | Number of milliseconds to wait before emitting a `RequestTimeoutError`                                                                                       |
| `baseUrl`       | `"https://api.krubkrong.com"` | `string`     | The root URL for sending API requests. This can be changed to test with a mock server.                                                                       |
| `logger`        | Log to console                | `Logger`     | A custom logging function. This function is only called when the client emits a log that is equal or greater severity than `logLevel`.                       |
| `agent`         | Default node agent            | `http.Agent` | Used to control creation of TCP sockets. A common use is to proxy requests with [`https-proxy-agent`](https://github.com/TooTallNate/node-https-proxy-agent) |