Socket
Socket
Sign inDemoInstall

@shopware/api-client

Package Overview
Dependencies
Maintainers
0
Versions
418
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@shopware/api-client - npm Package Compare versions

Comparing version 0.5.0 to 1.0.0

api-types/adminApiSchema.json

34

package.json
{
"name": "@shopware/api-client",
"version": "0.5.0",
"version": "1.0.0",
"description": "Shopware client for API connection.",
"author": "Shopware",
"type": "module",
"repository": {

@@ -38,16 +39,21 @@ "type": "git",

}
}
},
"./api-types": "./api-types/storeApiTypes.d.ts",
"./store-api-types": "./api-types/storeApiTypes.d.ts",
"./admin-api-types": "./api-types/adminApiTypes.d.ts"
},
"devDependencies": {
"@types/prettier": "^3.0.0",
"@vitest/coverage-c8": "^0.33.0",
"prettier": "^3.0.3",
"unbuild": "^2.0.0",
"vitest": "^0.34.6",
"@shopware/api-gen": "0.1.0",
"eslint-config-shopware": "0.0.7",
"@codspeed/vitest-plugin": "3.1.0",
"@types/prettier": "3.0.0",
"@vitest/coverage-v8": "1.6.0",
"prettier": "3.3.2",
"unbuild": "2.0.0",
"vitest": "1.6.0",
"eslint-config-shopware": "0.0.9",
"tsconfig": "0.0.0"
},
"dependencies": {
"ofetch": "^1.3.3"
"defu": "6.1.4",
"hookable": "5.5.3",
"ofetch": "1.3.4"
},

@@ -58,10 +64,10 @@ "scripts": {

"dev": "export NODE_ENV=development && unbuild --stub",
"generate": "esno ../api-gen/src/cli.ts generate",
"lint": "eslint src/**/*.ts* --fix --max-warnings=0 && pnpm run typecheck",
"typecheck": "tsc --noEmit",
"test": "vitest run && pnpm run test:types",
"test:types": "vitest typecheck --run",
"test": "vitest run --typecheck",
"test:bench": "vitest bench",
"test:watch": "vitest"
"test:watch": "vitest --typecheck",
"generate-types": "esno ../api-gen/src/cli.ts generate --apiType=store",
"generate-admin-types": "esno ../api-gen/src/cli.ts generate --apiType=admin"
}
}
# shopware/frontends - api-client
[![](https://img.shields.io/npm/v/@shopware/api-client?color=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o8L2RlZnM+Cjwvc3ZnPg==)](https://npmjs.com/package/@shopware/api-client)
[![](https://img.shields.io/github/package-json/v/shopware/frontends?color=blue&filename=packages%2Fapi-client-next%2Fpackage.json&label=frontends/api-client&logo=github)](https://github.com/shopware/frontends/tree/main/packages/api-client-next)
![](https://img.shields.io/github/license/shopware/frontends?color=blue)
[![](https://img.shields.io/github/package-json/v/shopware/frontends?color=blue&filename=packages%2Fapi-client%2Fpackage.json&label=frontends/api-client&logo=github)](https://github.com/shopware/frontends/tree/main/packages/api-client)
[![](https://img.shields.io/github/issues/shopware/frontends/api-client?label=package%20issues&logo=github)](https://github.com/shopware/frontends/issues?q=is%3Aopen+is%3Aissue+label%3Aapi-client)
[![](https://img.shields.io/github/license/shopware/frontends?color=blue)](#)
Dynamic and fully typed API Client for Shopware 6. Usable in any JavaScript an TypeScript project.
Dynamic and fully typed API Client for Shopware 6. Usable in any JavaScript and TypeScript project.
You can use types generated from your custom API instance to have autocompletion and type safety.
To generate your own types use [@shopware/api-gen](https://www.npmjs.com/package/@shopware/api-gen) CLI.
## Setup

@@ -15,15 +17,27 @@

```bash
# Using pnpm
pnpm add @shopware/api-client
<!-- automd:pm-install name="@shopware/api-client" -->
# Using yarn
```sh
# ✨ Auto-detect
npx nypm install @shopware/api-client
# npm
npm install @shopware/api-client
# yarn
yarn add @shopware/api-client
# Using npm
npm i @shopware/api-client
# pnpm
pnpm install @shopware/api-client
# bun
bun install @shopware/api-client
```
Recommended practice is to create separate module file. For example `src/apiClient.ts`, and import it whenever you need to use API Client.
<!-- /automd -->
## Store API client setup
Recommended practice is to create a separate module file. For example `src/apiClient.ts`, and import it whenever you need to use API Client.
```typescript

@@ -33,15 +47,5 @@ import { createAPIClient } from "@shopware/api-client";

// You can pick types of your current API version, the default one:
import type {
operationPaths,
operations,
components,
} from "@shopware/api-client/api-types";
// or (specific version):
import type {
operationPaths,
operations,
components,
} from "@shopware/api-client/api-types/apiTypes-6.4.20.0";
// or your types generated by @shopware/api-gen CLI:
import { operationPaths, operations, components } from "./apiTypes";
import type { operations } from "@shopware/api-client/store-api-types";
// or - RECOMMENDED - your types generated by [@shopware/api-gen](https://www.npmjs.com/package/@shopware/api-gen) CLI:
import type { operations } from "./api-types/storeApiTypes";

@@ -51,23 +55,16 @@ // you can pick cookies library of your choice

export const apiClient = createAPIClient<operations, operationPaths>({
export const apiClient = createAPIClient<operations>({
baseURL: "https://demo-frontends.shopware.store/store-api",
accessToken: "SWSCBHFSNTVMAWNZDNFKSHLAYW",
contextToken: Cookies.get("sw-context-token"),
onContextChanged(newContextToken) {
Cookies.set("sw-context-token", newContextToken, {
expires: 365, // days
path: "/",
sameSite: "lax",
});
},
});
// reimport schemas to use it in application
export type ApiSchemas = components["schemas"];
// reimport operations request parameters to use it in application
export type ApiRequestParams<OPERATION_NAME extends keyof operations> =
RequestParameters<OPERATION_NAME, operations>;
// reimport operations return types to use it in application
export type ApiReturnType<OPERATION_NAME extends keyof operations> =
RequestReturnType<OPERATION_NAME, operations>;
apiClient.hook("onContextChanged", (newContextToken) => {
Cookies.set("sw-context-token", newContextToken, {
expires: 365, // days
path: "/",
sameSite: "lax",
secure: shopwareEndpoint.startsWith("https://"),
});
});
```

@@ -77,37 +74,66 @@

The setup works the same way as `creteAPIClient` function, with few differences:
```typescript
import { createAdminAPIClient } from "@shopware/api-client";
```
The setup works the same way as `creteAPIClient` function, with few differences
### credentials (optional) - Quick scripting or token-based authentication
We provide optional `credentials` parameter to `createAdminAPIClient`. Which allows you to use authentication type of your choice whenever you wish to create connection to any endpoint.
Example:
```typescript
import type {
operations,
} from "@shopware/api-client/admin-api-types"; // we take default admin api types from different directory than store-api - use your own types by generating schema with @shopware/api-gen CLI
import type { operations } from "./api-types/adminApiTypes"; // or use your own types generated by @shopware/api-gen CLI
const adminApiClient = createAdminAPIClient<operations>({
baseURL: `${process.env.SHOP_URL}/api`,
credentials: {
grant_type: "password",
client_id: "administration",
scopes: "write",
username: process.env.SHOP_ADMIN_USERNAME,
password: process.env.SHOP_ADMIN_PASSWORD,
},
// credentials: { // or token-based example
// grant_type: "client_credentials",
// client_id: "administration",
// client_secret: process.env.SHOP_ADMIN_TOKEN,
// },
});
await adminApiClient.invoke(...); // invoke defined endpoint
```
### sessionData (optional) - Persistent authentication
This parameter is used to store session data in cookies (or other place you want to store it), so you can keep your session persistent.
You can combine this option with `credentials` property.
```typescript
// example adminApiClient.ts file
import { createAdminAPIClient } from "@shopware/api-client"; // we use different function to create admin api client
import {
RequestParameters,
RequestReturnType,
createAdminAPIClient,
} from "@shopware/api-client";
import type {
operationPaths,
operations,
components,
} from "@shopware/api-client/admin-api-types"; // we take default admin api types from different directory than store-api
import { createAdminAPIClient } from "@shopware/api-client";
import type { operations, Schemas } from "@shopware/api-client/admin-api-types"; // we take default admin api types from different directory than store-api
import Cookies from "js-cookie";
export const adminApiClient = createAdminAPIClient<operations, operationPaths>({
export const adminApiClient = createAdminAPIClient<operations>({
baseURL: "https://demo-frontends.shopware.store/api",
sessionData: JSON.parse(Cookies.get("sw-admin-session-data") || "{}"),
onAuthChange(sessionData) {
Cookies.set("sw-admin-session-data", JSON.stringify(sessionData), {
expires: 1, // days
path: "/",
sameSite: "lax",
});
},
});
export type AdminApiSchemas = components["schemas"];
export type AdminApiRequestParams<OPERATION_NAME extends keyof operations> =
RequestParameters<OPERATION_NAME, operations>;
export type AdminApiReturnType<OPERATION_NAME extends keyof operations> =
RequestReturnType<OPERATION_NAME, operations>;
adminApiClient.hooks("onAuthChange", (sessionData) => {
Cookies.set("sw-admin-session-data", JSON.stringify(sessionData), {
expires: 1, // days
path: "/",
sameSite: "lax",
secure: shopwareEndpoint.startsWith("https://"),
});
});
```

@@ -124,6 +150,6 @@

```typescript
import { apiClient, ApiReturnType } from "./apiClient";
import { apiClient, RequestReturnType } from "./apiClient";
// could be reactive value, you can use ApiReturnType to type it properly
let productsResponse: ApiReturnType<"readProduct">;
let productsResponse: RequestReturnType<"readProduct">;

@@ -137,2 +163,43 @@ async function loadProducts() {

### Fetch features
The new API client is leveraging [ofetch](https://github.com/unjs/ofetch) library, which has built in support for AbortController, timeout and other features.
Example usage of AbortController to cancell your request:
```typescript
const controller = new AbortController();
const request = client.invoke("readContext get /context", {
fetchOptions: {
signal: controller.signal,
},
});
controller.abort(); // At this point client will throw an error with the information, that the request has been cancelled
```
Other example of using `fetchOptions` for setting the timeout:
```typescript
const request = client.invoke("readContext get /context", {
fetchOptions: {
timeout: 5000, // 5 seconds
},
});
```
All exposed options available under `fetchOptions` are:
- `cache`
- `duplex`
- `keepalive`
- `priority`
- `redirect`
- `retry`
- `retryDelay`
- `retryStatusCodes`
- `signal`
- `timeout`
### Predefining methods

@@ -144,10 +211,21 @@

// add for example into apiClient.ts file
const readNavigation = (params: ApiRequestParams<"readNavigation">) =>
apiClient.invoke(
"readNavigation post /navigation/{activeId}/{rootId} sw-include-seo-urls",
{
depth: 2,
...params,
const readNavigation = ({
depth,
type,
}: {
depth: number;
type: "main-navigation";
}) =>
apiClient.invoke("readNavigation post /navigation/{activeId}/{rootId}", {
headers: {
"sw-include-seo-urls": true,
},
);
pathParams: {
activeId: type,
rootId: type,
},
body: {
depth,
},
});

@@ -159,4 +237,3 @@ // in another file you can use it, and depth property will be set to 2 by default

const navigation = await readNavigation({
activeId: "main-navigation",
rootId: "main-navigation",
body: { activeId: "main-navigation", rootId: "main-navigation" },
});

@@ -195,24 +272,71 @@ }

Full changelog for stable version is available [here](https://github.com/shopware/frontends/blob/main/packages/api-client-next/CHANGELOG.md)
Full changelog for stable version is available [here](https://github.com/shopware/frontends/blob/main/packages/api-client/CHANGELOG.md)
### Latest changes: 0.5.0
### Latest changes: 1.0.0
### Major Changes
- [#871](https://github.com/shopware/frontends/pull/871) [`1566f7a`](https://github.com/shopware/frontends/commit/1566f7a3962c511b5c72e12a4a5db40c4aa5d198) Thanks [@patzick](https://github.com/patzick)! - Read more about new major release: https://github.com/shopware/frontends/discussions/965
- [#1056](https://github.com/shopware/frontends/pull/1056) [`c729e70`](https://github.com/shopware/frontends/commit/c729e7014c70d7f71edf5297104065d18e482e04) Thanks [@patzick](https://github.com/patzick)! - Removed deprecations from the code:
- `onContextChanged` function inside `createAPIClient` method. Use `apiClient.hook("onContextChanged", ...)` instead.
- `apiType` flag from the `createAPIClient`. Use separate methods to create store and admin api clients
- `onAuthChange` from the `createAdminAPIClient`. Use `adminApiClient.hook('onAuthChange',...)` instead
### Minor Changes
- [#435](https://github.com/shopware/frontends/pull/435) [`a4483ed8`](https://github.com/shopware/frontends/commit/a4483ed8bf9370e87aedeb81846fe9d31880b3e0) Thanks [@patzick](https://github.com/patzick)! - Changed types imports to `import type {...} from "..."`
- [#1039](https://github.com/shopware/frontends/pull/1039) [`2343012`](https://github.com/shopware/frontends/commit/2343012ad552b06557e6715055b3abc534fa2fae) Thanks [@patzick](https://github.com/patzick)! - We're exposing `fetchOptions` inside params of `invoke` method. You can now use `ofetch` features like `timeout` or `signal` with AbortController
### Patch Changes
Example for the AbortController:
- [#443](https://github.com/shopware/frontends/pull/443) [`33d54db1`](https://github.com/shopware/frontends/commit/33d54db1bd66146a14781c45b1124547f4276866) Thanks [@patzick](https://github.com/patzick)! - `invoke` method parameters are no longer mandatory when no parameters are defined inside route.
```ts
const controller = new AbortController();
Now instead of:
const request = client.invoke("readContext get /context", {
fetchOptions: {
signal: controller.signal,
},
});
```ts
const result = await apiInstance.invoke("readContext get /context", {});
controller.abort(); // At this point client will throw an error with the information, that the request has been cancelled
```
you can do:
- [#560](https://github.com/shopware/frontends/pull/560) [`9643e56`](https://github.com/shopware/frontends/commit/9643e56dafba9282b75c12c96b2afb3a4738f86e) Thanks [@patzick](https://github.com/patzick)! - [createAdminAPIClient] ability to pass optional field `credentials` to be used as authentication method before invoking any Admin API endpoint.
- [#639](https://github.com/shopware/frontends/pull/639) [`d60d062`](https://github.com/shopware/frontends/commit/d60d0620c7114a2f26bb2faf24241e2cbabc8798) Thanks [@patzick](https://github.com/patzick)! - Management of defaultHeaders. You can now set them on apiClient init or runtime.
```ts
const result = await apiInstance.invoke("readContext get /context");
const apiClient = createApiClient({
...,
defaultHeaders: {
'sw-language-id': 'my-id',
},
});
console.log('Debug default headers:', apiClient.defaultHeaders);
// Change header runtime
apiClient.defaultHeaders['sw-language-id'] = 'my-new-id';
// Remove header runtime
apiClient.defaultHeaders['sw-language-id'] = "";
// Change multiple headers runtime
apiClient.defaultHeaders.apply({
'sw-language-id': 'another-id',
'sw-currency-id': 'currency-id',
})
```
- [#857](https://github.com/shopware/frontends/pull/857) [`864616f`](https://github.com/shopware/frontends/commit/864616f0c9e1cbe11e434b9a04a35ff9520bcb3c) Thanks [@mdanilowicz](https://github.com/mdanilowicz)! - Add error and success callbacks
### Patch Changes
- [#787](https://github.com/shopware/frontends/pull/787) [`782ef4d`](https://github.com/shopware/frontends/commit/782ef4d417dce6e6d60992bd54f876aa4bc5f45d) Thanks [@mkucmus](https://github.com/mkucmus)! - Adjust test snapshot for Shopware v6.6 response
- [#567](https://github.com/shopware/frontends/pull/567) [`1583a7a`](https://github.com/shopware/frontends/commit/1583a7ae0d68b72fb362b625e1634e03bad68110) Thanks [@patzick](https://github.com/patzick)! - Export default API types to be compatible with the `bundler` mode resolution in `tsconfig`
- [#557](https://github.com/shopware/frontends/pull/557) [`97d2859`](https://github.com/shopware/frontends/commit/97d2859e4dcbdc563200f2f64d1a20880b675d87) Thanks [@patzick](https://github.com/patzick)! - Added `Accept: application/json` default header to get only JSON responses.
- [`89a97a4`](https://github.com/shopware/frontends/commit/89a97a45ae4a58616e41f63e9884a2a67f0a6ce8) Thanks [@patzick](https://github.com/patzick)! - fix default types

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc