@shopware/api-client 0.4.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,111 +1,137 @@
1
1
  # shopware/frontends - api-client
2
2
 
3
3
  [![](https://img.shields.io/npm/v/@shopware/api-client?color=blue&logo=data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIiIGhlaWdodD0iMTIiIHZpZXdCb3g9IjAgMCA0ODggNTUzIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBkPSJNNDM5LjA0MSAxMjkuNTkzTDI1OC43NjkgMzEuMzA3NkMyNDQuOTE1IDIzLjc1NDEgMjI4LjExNiAyNC4wMDkzIDIxNC40OTcgMzEuOTgwMkw0Ny4yNjkgMTI5Ljg1OEMzMy40NzYzIDEzNy45MzEgMjUgMTUyLjcxMyAyNSAxNjguNjk1VjM4OC40NjZDMjUgNDA0LjczMiAzMy43Nzg1IDQxOS43MzIgNDcuOTYwMiA0MjcuNjk5TDIxNS4xNzggNTIxLjYzNkMyMjguNDUxIDUyOS4wOTIgMjQ0LjU5MyA1MjkuMzMyIDI1OC4wODIgNTIyLjI3NEw0MzguMzY0IDQyNy45MzRDNDUzLjIwMSA0MjAuMTcgNDYyLjUgNDA0LjgwOSA0NjIuNSAzODguMDYzVjE2OS4xMDJDNDYyLjUgMTUyLjYzMiA0NTMuNTAyIDEzNy40NzcgNDM5LjA0MSAxMjkuNTkzWiIgc3Ryb2tlPSJ1cmwoI3BhaW50MF9saW5lYXJfMTUzXzY5MjY1KSIgc3Ryb2tlLXdpZHRoPSI1MCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIvPgo8ZGVmcz4KPGxpbmVhckdyYWRpZW50IGlkPSJwYWludDBfbGluZWFyXzE1M182OTI2NSIgeDE9Ii0xNi4yOTg5IiB5MT0iMTY1LjM0OSIgeDI9IjI3Ni40MTIiIHkyPSItODkuMzIzNCIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPgo8c3RvcCBzdG9wLWNvbG9yPSIjMDA4NUZGIi8+CjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iI0MwRTJGNSIvPgo8L2xpbmVhckdyYWRpZW50Pgo8L2RlZnM+Cjwvc3ZnPg==)](https://npmjs.com/package/@shopware/api-client)
4
- [![](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)
5
- ![](https://img.shields.io/github/license/shopware/frontends?color=blue)
4
+ [![](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)
6
5
  [![](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)
6
+ [![](https://img.shields.io/github/license/shopware/frontends?color=blue)](#)
7
7
 
8
- Dynamic and fully typed API Client for Shopware 6. Usable in any JavaScript an TypeScript project.
8
+ Dynamic and fully typed API Client for Shopware 6. Usable in any JavaScript and TypeScript project.
9
9
  You can use types generated from your custom API instance to have autocompletion and type safety.
10
10
 
11
+ To generate your own types use [@shopware/api-gen](https://www.npmjs.com/package/@shopware/api-gen) CLI.
12
+
11
13
  ## Setup
12
14
 
13
15
  Install npm package:
14
16
 
15
- ```bash
16
- # Using pnpm
17
- pnpm add @shopware/api-client
17
+ <!-- automd:pm-install name="@shopware/api-client" -->
18
+
19
+ ```sh
20
+ # ✨ Auto-detect
21
+ npx nypm install @shopware/api-client
22
+
23
+ # npm
24
+ npm install @shopware/api-client
18
25
 
19
- # Using yarn
26
+ # yarn
20
27
  yarn add @shopware/api-client
21
28
 
22
- # Using npm
23
- npm i @shopware/api-client
29
+ # pnpm
30
+ pnpm install @shopware/api-client
31
+
32
+ # bun
33
+ bun install @shopware/api-client
24
34
  ```
25
35
 
26
- Recommended practice is to create separate module file. For example `src/apiClient.ts`, and import it whenever you need to use API Client.
36
+ <!-- /automd -->
37
+
38
+ ## Store API client setup
39
+
40
+ Recommended practice is to create a separate module file. For example `src/apiClient.ts`, and import it whenever you need to use API Client.
27
41
 
28
42
  ```typescript
29
43
  import { createAPIClient } from "@shopware/api-client";
30
44
 
31
45
  // You can pick types of your current API version, the default one:
32
- import {
33
- operationPaths,
34
- operations,
35
- components,
36
- } from "@shopware/api-client/api-types";
37
- // or (specific version):
38
- import {
39
- operationPaths,
40
- operations,
41
- components,
42
- } from "@shopware/api-client/api-types/apiTypes-6.4.20.0";
43
- // or your types generated by @shopware/api-gen CLI:
44
- import { operationPaths, operations, components } from "./apiTypes";
46
+ import type { operations } from "@shopware/api-client/store-api-types";
47
+ // or - RECOMMENDED - your types generated by [@shopware/api-gen](https://www.npmjs.com/package/@shopware/api-gen) CLI:
48
+ import type { operations } from "./api-types/storeApiTypes";
45
49
 
46
50
  // you can pick cookies library of your choice
47
51
  import Cookies from "js-cookie";
48
52
 
49
- export const apiClient = createAPIClient<operations, operationPaths>({
53
+ export const apiClient = createAPIClient<operations>({
50
54
  baseURL: "https://demo-frontends.shopware.store/store-api",
51
55
  accessToken: "SWSCBHFSNTVMAWNZDNFKSHLAYW",
52
56
  contextToken: Cookies.get("sw-context-token"),
53
- onContextChanged(newContextToken) {
54
- Cookies.set("sw-context-token", newContextToken, {
55
- expires: 365, // days
56
- path: "/",
57
- sameSite: "lax",
58
- });
59
- },
60
57
  });
61
58
 
62
- // reimport schemas to use it in application
63
- export type ApiSchemas = components["schemas"];
64
- // reimport operations request parameters to use it in application
65
- export type ApiRequestParams<OPERATION_NAME extends keyof operations> =
66
- RequestParameters<OPERATION_NAME, operations>;
67
- // reimport operations return types to use it in application
68
- export type ApiReturnType<OPERATION_NAME extends keyof operations> =
69
- RequestReturnType<OPERATION_NAME, operations>;
59
+ apiClient.hook("onContextChanged", (newContextToken) => {
60
+ Cookies.set("sw-context-token", newContextToken, {
61
+ expires: 365, // days
62
+ path: "/",
63
+ sameSite: "lax",
64
+ secure: shopwareEndpoint.startsWith("https://"),
65
+ });
66
+ });
70
67
  ```
71
68
 
72
69
  ## Admin API client setup
73
70
 
74
- The setup works the same way as `creteAPIClient` function, with few differences:
71
+ ```typescript
72
+ import { createAdminAPIClient } from "@shopware/api-client";
73
+ ```
74
+
75
+ The setup works the same way as `creteAPIClient` function, with few differences
76
+
77
+ ### credentials (optional) - Quick scripting or token-based authentication
78
+
79
+ 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.
80
+
81
+ Example:
82
+
83
+ ```typescript
84
+ import type {
85
+ operations,
86
+ } 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
87
+ import type { operations } from "./api-types/adminApiTypes"; // or use your own types generated by @shopware/api-gen CLI
88
+
89
+ const adminApiClient = createAdminAPIClient<operations>({
90
+ baseURL: `${process.env.SHOP_URL}/api`,
91
+ credentials: {
92
+ grant_type: "password",
93
+ client_id: "administration",
94
+ scopes: "write",
95
+ username: process.env.SHOP_ADMIN_USERNAME,
96
+ password: process.env.SHOP_ADMIN_PASSWORD,
97
+ },
98
+ // credentials: { // or token-based example
99
+ // grant_type: "client_credentials",
100
+ // client_id: "administration",
101
+ // client_secret: process.env.SHOP_ADMIN_TOKEN,
102
+ // },
103
+ });
104
+
105
+ await adminApiClient.invoke(...); // invoke defined endpoint
106
+ ```
107
+
108
+ ### sessionData (optional) - Persistent authentication
109
+
110
+ 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.
111
+
112
+ You can combine this option with `credentials` property.
75
113
 
76
114
  ```typescript
77
115
  // example adminApiClient.ts file
78
116
  import { createAdminAPIClient } from "@shopware/api-client"; // we use different function to create admin api client
79
117
 
80
- import {
81
- RequestParameters,
82
- RequestReturnType,
83
- createAdminAPIClient,
84
- } from "@shopware/api-client";
85
- import {
86
- operationPaths,
87
- operations,
88
- components,
89
- } from "@shopware/api-client/admin-api-types"; // we take default admin api types from different directory than store-api
118
+ import { createAdminAPIClient } from "@shopware/api-client";
119
+ import type { operations, Schemas } from "@shopware/api-client/admin-api-types"; // we take default admin api types from different directory than store-api
90
120
  import Cookies from "js-cookie";
91
121
 
92
- export const adminApiClient = createAdminAPIClient<operations, operationPaths>({
122
+ export const adminApiClient = createAdminAPIClient<operations>({
93
123
  baseURL: "https://demo-frontends.shopware.store/api",
94
124
  sessionData: JSON.parse(Cookies.get("sw-admin-session-data") || "{}"),
95
- onAuthChange(sessionData) {
96
- Cookies.set("sw-admin-session-data", JSON.stringify(sessionData), {
97
- expires: 1, // days
98
- path: "/",
99
- sameSite: "lax",
100
- });
101
- },
102
125
  });
103
126
 
104
- export type AdminApiSchemas = components["schemas"];
105
- export type AdminApiRequestParams<OPERATION_NAME extends keyof operations> =
106
- RequestParameters<OPERATION_NAME, operations>;
107
- export type AdminApiReturnType<OPERATION_NAME extends keyof operations> =
108
- RequestReturnType<OPERATION_NAME, operations>;
127
+ adminApiClient.hooks("onAuthChange", (sessionData) => {
128
+ Cookies.set("sw-admin-session-data", JSON.stringify(sessionData), {
129
+ expires: 1, // days
130
+ path: "/",
131
+ sameSite: "lax",
132
+ secure: shopwareEndpoint.startsWith("https://"),
133
+ });
134
+ });
109
135
  ```
110
136
 
111
137
  the rest works the same as store-api client.
@@ -117,10 +143,10 @@ Take a look at [example project using API Client](https://stackblitz.com/github/
117
143
  ### Simple invocation
118
144
 
119
145
  ```typescript
120
- import { apiClient, ApiReturnType } from "./apiClient";
146
+ import { apiClient, RequestReturnType } from "./apiClient";
121
147
 
122
148
  // could be reactive value, you can use ApiReturnType to type it properly
123
- let productsResponse: ApiReturnType<"readProduct">;
149
+ let productsResponse: RequestReturnType<"readProduct">;
124
150
 
125
151
  async function loadProducts() {
126
152
  productsResponse = await apiClient.invoke("readProduct post /product", {
@@ -129,28 +155,79 @@ async function loadProducts() {
129
155
  }
130
156
  ```
131
157
 
158
+ ### Fetch features
159
+
160
+ The new API client is leveraging [ofetch](https://github.com/unjs/ofetch) library, which has built in support for AbortController, timeout and other features.
161
+
162
+ Example usage of AbortController to cancell your request:
163
+
164
+ ```typescript
165
+ const controller = new AbortController();
166
+
167
+ const request = client.invoke("readContext get /context", {
168
+ fetchOptions: {
169
+ signal: controller.signal,
170
+ },
171
+ });
172
+
173
+ controller.abort(); // At this point client will throw an error with the information, that the request has been cancelled
174
+ ```
175
+
176
+ Other example of using `fetchOptions` for setting the timeout:
177
+
178
+ ```typescript
179
+ const request = client.invoke("readContext get /context", {
180
+ fetchOptions: {
181
+ timeout: 5000, // 5 seconds
182
+ },
183
+ });
184
+ ```
185
+
186
+ All exposed options available under `fetchOptions` are:
187
+
188
+ - `cache`
189
+ - `duplex`
190
+ - `keepalive`
191
+ - `priority`
192
+ - `redirect`
193
+ - `retry`
194
+ - `retryDelay`
195
+ - `retryStatusCodes`
196
+ - `signal`
197
+ - `timeout`
198
+
132
199
  ### Predefining methods
133
200
 
134
201
  If you prefer to add another layer of abstraction you can use created previously types to define your own concept of methods.
135
202
 
136
203
  ```typescript
137
204
  // add for example into apiClient.ts file
138
- const readNavigation = (params: ApiRequestParams<"readNavigation">) =>
139
- apiClient.invoke(
140
- "readNavigation post /navigation/{activeId}/{rootId} sw-include-seo-urls",
141
- {
142
- depth: 2,
143
- ...params,
205
+ const readNavigation = ({
206
+ depth,
207
+ type,
208
+ }: {
209
+ depth: number;
210
+ type: "main-navigation";
211
+ }) =>
212
+ apiClient.invoke("readNavigation post /navigation/{activeId}/{rootId}", {
213
+ headers: {
214
+ "sw-include-seo-urls": true,
215
+ },
216
+ pathParams: {
217
+ activeId: type,
218
+ rootId: type,
144
219
  },
145
- );
220
+ body: {
221
+ depth,
222
+ },
223
+ });
146
224
 
147
225
  // in another file you can use it, and depth property will be set to 2 by default
148
226
  import { readNavigation } from "./apiClient";
149
227
 
150
228
  async function loadMainNavigation() {
151
229
  const navigation = await readNavigation({
152
- activeId: "main-navigation",
153
- rootId: "main-navigation",
230
+ body: { activeId: "main-navigation", rootId: "main-navigation" },
154
231
  });
155
232
  }
156
233
  ```
@@ -184,26 +261,73 @@ try {
184
261
 
185
262
  ## Changelog
186
263
 
187
- Full changelog for stable version is available [here](https://github.com/shopware/frontends/blob/main/packages/api-client-next/CHANGELOG.md)
264
+ Full changelog for stable version is available [here](https://github.com/shopware/frontends/blob/main/packages/api-client/CHANGELOG.md)
265
+
266
+ ### Latest changes: 1.0.0
267
+
268
+ ### Major Changes
188
269
 
189
- ### Latest changes: 0.4.0
270
+ - [#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
271
+
272
+ - [#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:
273
+
274
+ - `onContextChanged` function inside `createAPIClient` method. Use `apiClient.hook("onContextChanged", ...)` instead.
275
+ - `apiType` flag from the `createAPIClient`. Use separate methods to create store and admin api clients
276
+ - `onAuthChange` from the `createAdminAPIClient`. Use `adminApiClient.hook('onAuthChange',...)` instead
190
277
 
191
278
  ### Minor Changes
192
279
 
193
- - [#371](https://github.com/shopware/frontends/pull/371) [`83c94e9b`](https://github.com/shopware/frontends/commit/83c94e9bb609533c4a1275cbf3822b0fc2ea1dd5) Thanks [@patzick](https://github.com/patzick)! - New method `createAdminAPIClient` supporting Admin API 🅰🅿🅸
280
+ - [#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
194
281
 
195
- - [#373](https://github.com/shopware/frontends/pull/373) [`5510bb02`](https://github.com/shopware/frontends/commit/5510bb028b1fea4c63d677850f50bb7b5a1cf01a) Thanks [@patzick](https://github.com/patzick)! - Added `getSessionData` and `setSessionData` methods in admin API client for test purposes.
282
+ Example for the AbortController:
196
283
 
197
- ### Patch Changes
284
+ ```ts
285
+ const controller = new AbortController();
198
286
 
199
- - [#385](https://github.com/shopware/frontends/pull/385) [`5d7e7973`](https://github.com/shopware/frontends/commit/5d7e7973437a4d74d19ec2fa0765c6d927bf8b2a) Thanks [@patzick](https://github.com/patzick)! - Dependency changes:
287
+ const request = client.invoke("readContext get /context", {
288
+ fetchOptions: {
289
+ signal: controller.signal,
290
+ },
291
+ });
200
292
 
201
- - Changed dependency _ofetch_ from **^1.2.1** to **^1.3.3**
293
+ controller.abort(); // At this point client will throw an error with the information, that the request has been cancelled
294
+ ```
295
+
296
+ - [#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.
297
+
298
+ - [#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.
299
+
300
+ ```ts
301
+ const apiClient = createApiClient({
302
+ ...,
303
+ defaultHeaders: {
304
+ 'sw-language-id': 'my-id',
305
+ },
306
+ });
307
+
308
+ console.log('Debug default headers:', apiClient.defaultHeaders);
309
+
310
+ // Change header runtime
311
+ apiClient.defaultHeaders['sw-language-id'] = 'my-new-id';
312
+
313
+ // Remove header runtime
314
+ apiClient.defaultHeaders['sw-language-id'] = "";
315
+
316
+ // Change multiple headers runtime
317
+ apiClient.defaultHeaders.apply({
318
+ 'sw-language-id': 'another-id',
319
+ 'sw-currency-id': 'currency-id',
320
+ })
321
+ ```
322
+
323
+ - [#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
324
+
325
+ ### Patch Changes
202
326
 
203
- - [#375](https://github.com/shopware/frontends/pull/375) [`bd88d6fa`](https://github.com/shopware/frontends/commit/bd88d6fa95de2b90f8a1e08e34159b46c5932b3b) Thanks [@patzick](https://github.com/patzick)! - Dependency changes:
327
+ - [#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
204
328
 
205
- - Changed dependency _ofetch_ from **^1.1.1** to **^1.2.1**
329
+ - [#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`
206
330
 
207
- - [`15d6e696`](https://github.com/shopware/frontends/commit/15d6e69616bd9bc5ad32f2a5f697e00c45a94784) Thanks [@patzick](https://github.com/patzick)! - Emit cjs bundle
331
+ - [#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.
208
332
 
209
- - [#371](https://github.com/shopware/frontends/pull/371) [`83c94e9b`](https://github.com/shopware/frontends/commit/83c94e9bb609533c4a1275cbf3822b0fc2ea1dd5) Thanks [@patzick](https://github.com/patzick)! - Deprecated `apiType` param in `createAPIClient`, for Admin API client use `createAdminAPIClient` instead.
333
+ - [`89a97a4`](https://github.com/shopware/frontends/commit/89a97a45ae4a58616e41f63e9884a2a67f0a6ce8) Thanks [@patzick](https://github.com/patzick)! - fix default types