@teamnovu/kit-shopware-api-client 0.0.3 → 0.0.4

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/dist/client.d.ts CHANGED
@@ -1,14 +1,10 @@
1
1
  import { EventEmitter } from './eventEmitter';
2
2
  import { OperationOptions, OperationProp, ShopwareClientOptions } from './types';
3
- export declare class ShopwareApiError extends Error {
4
- readonly status: number;
5
- readonly response?: unknown | undefined;
6
- constructor(message: string, status: number, response?: unknown | undefined);
3
+ export interface ResponseType<TKey> {
4
+ __response: TKey;
7
5
  }
8
- export declare class ShopwareClient<Operations extends Record<string, {
9
- body?: unknown;
10
- response?: unknown;
11
- }>> extends EventEmitter {
6
+ export type BrandedResponse<Operations, OperationKey extends (keyof Operations) & string> = ResponseType<OperationKey> & OperationProp<Operations, OperationKey, 'response'>;
7
+ export declare class ShopwareClient<Operations> extends EventEmitter {
12
8
  private options;
13
9
  constructor(options: ShopwareClientOptions);
14
10
  setBaseURL(baseURL: string): void;
@@ -19,5 +15,6 @@ export declare class ShopwareClient<Operations extends Record<string, {
19
15
  setReflectContextToken(reflectContextToken?: boolean): void;
20
16
  private parseOperation;
21
17
  private interpolateUrl;
22
- query<OperationKey extends (keyof Operations) & string>(operation: OperationKey, options?: OperationOptions<Operations, OperationKey>): Promise<OperationProp<Operations, OperationKey, 'response'>>;
18
+ queryRaw<OperationKey extends (keyof Operations) & string>(operation: OperationKey, options?: OperationOptions<Operations, OperationKey>): Promise<Response>;
19
+ query<OperationKey extends (keyof Operations) & string>(operation: OperationKey, options?: OperationOptions<Operations, OperationKey>): Promise<BrandedResponse<Operations, OperationKey>>;
23
20
  }
@@ -0,0 +1,64 @@
1
+ import { z } from 'zod';
2
+ declare const shopwareErrorSchema: z.ZodObject<{
3
+ status: z.ZodString;
4
+ code: z.ZodString;
5
+ title: z.ZodOptional<z.ZodString>;
6
+ detail: z.ZodOptional<z.ZodString>;
7
+ meta: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
8
+ source: z.ZodOptional<z.ZodObject<{
9
+ pointer: z.ZodOptional<z.ZodString>;
10
+ }, "strip", z.ZodTypeAny, {
11
+ pointer?: string | undefined;
12
+ }, {
13
+ pointer?: string | undefined;
14
+ }>>;
15
+ trace: z.ZodOptional<z.ZodArray<z.ZodObject<{
16
+ file: z.ZodString;
17
+ line: z.ZodNumber;
18
+ function: z.ZodString;
19
+ }, "strip", z.ZodTypeAny, {
20
+ function: string;
21
+ file: string;
22
+ line: number;
23
+ }, {
24
+ function: string;
25
+ file: string;
26
+ line: number;
27
+ }>, "many">>;
28
+ }, "strip", z.ZodTypeAny, {
29
+ status: string;
30
+ code: string;
31
+ title?: string | undefined;
32
+ detail?: string | undefined;
33
+ meta?: Record<string, unknown> | undefined;
34
+ source?: {
35
+ pointer?: string | undefined;
36
+ } | undefined;
37
+ trace?: {
38
+ function: string;
39
+ file: string;
40
+ line: number;
41
+ }[] | undefined;
42
+ }, {
43
+ status: string;
44
+ code: string;
45
+ title?: string | undefined;
46
+ detail?: string | undefined;
47
+ meta?: Record<string, unknown> | undefined;
48
+ source?: {
49
+ pointer?: string | undefined;
50
+ } | undefined;
51
+ trace?: {
52
+ function: string;
53
+ file: string;
54
+ line: number;
55
+ }[] | undefined;
56
+ }>;
57
+ export type ShopwareError = z.infer<typeof shopwareErrorSchema>;
58
+ export declare class ShopwareApiError extends Error {
59
+ readonly status: number;
60
+ readonly response?: unknown | undefined;
61
+ errors: ShopwareError[];
62
+ constructor(message: string, status: number, response?: unknown | undefined);
63
+ }
64
+ export {};
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './client';
2
2
  export * from './types';
3
+ export { type ShopwareError, ShopwareApiError } from './error';
package/dist/index.mjs CHANGED
@@ -1,96 +1,136 @@
1
- var u = Object.defineProperty;
2
- var p = (o, t, e) => t in o ? u(o, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : o[t] = e;
3
- var c = (o, t, e) => p(o, typeof t != "symbol" ? t + "" : t, e);
4
- class d {
1
+ var d = Object.defineProperty;
2
+ var g = (i, r, e) => r in i ? d(i, r, { enumerable: !0, configurable: !0, writable: !0, value: e }) : i[r] = e;
3
+ var u = (i, r, e) => g(i, typeof r != "symbol" ? r + "" : r, e);
4
+ import { z as o } from "zod";
5
+ const y = o.object({
6
+ status: o.string(),
7
+ code: o.string(),
8
+ title: o.string().optional(),
9
+ detail: o.string().optional(),
10
+ meta: o.record(o.unknown()).optional(),
11
+ source: o.object({
12
+ pointer: o.string().optional()
13
+ }).optional(),
14
+ trace: o.array(
15
+ o.object({
16
+ file: o.string(),
17
+ line: o.number(),
18
+ function: o.string()
19
+ })
20
+ ).optional()
21
+ }), w = o.object({
22
+ errors: o.array(y)
23
+ });
24
+ class p extends Error {
25
+ constructor(e, t, s) {
26
+ super(e);
27
+ u(this, "errors");
28
+ this.status = t, this.response = s, this.name = "ShopwareApiError";
29
+ const { success: n, data: a } = w.safeParse(s);
30
+ this.errors = n ? a.errors : [];
31
+ }
32
+ }
33
+ class m {
5
34
  constructor() {
6
- c(this, "listeners", /* @__PURE__ */ new Map());
35
+ u(this, "listeners", /* @__PURE__ */ new Map());
7
36
  }
8
- addEventListener(t, e, s) {
37
+ addEventListener(r, e, t) {
9
38
  if (!e) return;
10
- const n = this.normalizeOptions(s), r = {
39
+ const s = this.normalizeOptions(t), n = {
11
40
  listener: e,
12
- options: n
41
+ options: s
13
42
  };
14
- if (n.signal) {
15
- if (n.signal.aborted) return;
16
- r.signal = n.signal, n.signal.addEventListener("abort", () => {
17
- this.removeEventListener(t, e, s);
43
+ if (s.signal) {
44
+ if (s.signal.aborted) return;
45
+ n.signal = s.signal, s.signal.addEventListener("abort", () => {
46
+ this.removeEventListener(r, e, t);
18
47
  }, { once: !0 });
19
48
  }
20
- this.listeners.has(t) || this.listeners.set(t, []), this.listeners.get(t).push(r);
49
+ this.listeners.has(r) || this.listeners.set(r, []), this.listeners.get(r).push(n);
21
50
  }
22
- removeEventListener(t, e, s) {
51
+ removeEventListener(r, e, t) {
23
52
  if (!e) return;
24
- const n = this.listeners.get(t);
25
- if (!n) return;
26
- const r = this.normalizeOptions(s), a = n.findIndex((i) => i.listener === e && this.optionsMatch(i.options, r));
27
- a !== -1 && (n.splice(a, 1), n.length === 0 && this.listeners.delete(t));
28
- }
29
- dispatchEvent(t) {
30
- var n;
31
- const e = this.listeners.get(t.type);
53
+ const s = this.listeners.get(r);
54
+ if (!s) return;
55
+ const n = this.normalizeOptions(t), a = s.findIndex((h) => h.listener === e && this.optionsMatch(h.options, n));
56
+ a !== -1 && (s.splice(a, 1), s.length === 0 && this.listeners.delete(r));
57
+ }
58
+ dispatchEvent(r) {
59
+ var s;
60
+ const e = this.listeners.get(r.type);
32
61
  if (!e || e.length === 0) return !0;
33
- const s = [...e];
34
- for (const r of s)
35
- if (!((n = r.signal) != null && n.aborted)) {
62
+ const t = [...e];
63
+ for (const n of t)
64
+ if (!((s = n.signal) != null && s.aborted)) {
36
65
  try {
37
- typeof r.listener == "function" ? r.listener.call(this, t) : r.listener.handleEvent(t);
66
+ typeof n.listener == "function" ? n.listener.call(this, r) : n.listener.handleEvent(r);
38
67
  } catch (a) {
39
68
  console.error("Error in event listener:", a);
40
69
  }
41
- if (r.options.once && this.removeEventListener(t.type, r.listener, r.options), t.cancelBubble) break;
70
+ if (n.options.once && this.removeEventListener(r.type, n.listener, n.options), r.cancelBubble) break;
42
71
  }
43
- return !t.defaultPrevented;
72
+ return !r.defaultPrevented;
44
73
  }
45
- normalizeOptions(t) {
46
- return typeof t == "boolean" ? { capture: t } : {
74
+ normalizeOptions(r) {
75
+ return typeof r == "boolean" ? { capture: r } : {
47
76
  capture: !1,
48
77
  once: !1,
49
78
  passive: !1,
50
- ...t
79
+ ...r
51
80
  };
52
81
  }
53
- optionsMatch(t, e) {
54
- return t.capture === e.capture;
82
+ optionsMatch(r, e) {
83
+ return r.capture === e.capture;
55
84
  }
56
85
  // Utility methods for easier usage
57
- on(t, e, s) {
58
- this.addEventListener(t, e, s);
86
+ on(r, e, t) {
87
+ this.addEventListener(r, e, t);
59
88
  }
60
- off(t, e, s) {
61
- this.removeEventListener(t, e, s);
89
+ off(r, e, t) {
90
+ this.removeEventListener(r, e, t);
62
91
  }
63
- once(t, e, s) {
64
- const n = typeof s == "boolean" ? {
65
- capture: s,
92
+ once(r, e, t) {
93
+ const s = typeof t == "boolean" ? {
94
+ capture: t,
66
95
  once: !0
67
96
  } : {
68
- ...s,
97
+ ...t,
69
98
  once: !0
70
99
  };
71
- this.addEventListener(t, e, n);
100
+ this.addEventListener(r, e, s);
72
101
  }
73
- emit(t, e) {
74
- const s = new CustomEvent(t, { detail: e });
75
- return this.dispatchEvent(s);
102
+ emit(r, e) {
103
+ const t = new CustomEvent(r, { detail: e });
104
+ return this.dispatchEvent(t);
76
105
  }
77
106
  getEventTypes() {
78
107
  return Array.from(this.listeners.keys());
79
108
  }
80
- removeAllListeners(t) {
81
- t ? this.listeners.delete(t) : this.listeners.clear();
109
+ removeAllListeners(r) {
110
+ r ? this.listeners.delete(r) : this.listeners.clear();
82
111
  }
83
112
  }
84
- class h extends Error {
85
- constructor(t, e, s) {
86
- super(t), this.status = e, this.response = s, this.name = "ShopwareApiError";
87
- }
113
+ const f = (i) => i == null || typeof i == "number" && isNaN(i) || typeof i == "function";
114
+ function b(i) {
115
+ const r = new URLSearchParams(), e = (t, s) => {
116
+ f(s) || (typeof s == "object" && r.append(t, JSON.stringify(s)), r.append(t, String(s)));
117
+ };
118
+ for (const [t, s] of Object.entries(i))
119
+ if (!f(s))
120
+ if (typeof s == "string")
121
+ r.append(t, String(s));
122
+ else if (Array.isArray(s))
123
+ for (const n of s)
124
+ e(`${t}[]`, n);
125
+ else
126
+ e(t, s);
127
+ return r;
88
128
  }
89
- const f = /^(?<name>\w+?)\s(?<method>get|post|put|patch|delete)\s+(?<url>\/.*)/i;
90
- class v extends d {
129
+ const E = /^(?<name>\w+?)\s(?<method>get|post|put|patch|delete)\s+(?<url>\/.*)/i;
130
+ class v extends m {
91
131
  constructor(e) {
92
132
  super();
93
- c(this, "options", {
133
+ u(this, "options", {
94
134
  baseURL: "",
95
135
  apiKey: "",
96
136
  language: "",
@@ -118,7 +158,7 @@ class v extends d {
118
158
  setContextToken(e) {
119
159
  if (e && typeof e != "string")
120
160
  throw new Error("Invalid contextToken: If provided, it must be a string.");
121
- this.options.contextToken = e;
161
+ this.options.contextToken = e, this.emit("contextToken", e);
122
162
  }
123
163
  setIncludeSeoUrls(e = !0) {
124
164
  this.options.includeSeoUrls = e;
@@ -127,59 +167,64 @@ class v extends d {
127
167
  this.options.reflectContextToken = e;
128
168
  }
129
169
  parseOperation(e) {
130
- const s = f.exec(e);
131
- if (!(s != null && s.groups))
170
+ const t = E.exec(e);
171
+ if (!(t != null && t.groups))
132
172
  throw new Error("Invalid operation format");
133
173
  return {
134
- name: s.groups.name,
135
- method: s.groups.method.toUpperCase(),
136
- url: s.groups.url
174
+ name: t.groups.name,
175
+ method: t.groups.method.toUpperCase(),
176
+ url: t.groups.url
137
177
  };
138
178
  }
139
- interpolateUrl(e, s) {
140
- return e.replace(/{([^}]+?)}/g, (n, r) => {
141
- if (!(r in s))
142
- throw new Error(`Missing required URL parameter: ${r}`);
143
- return s[r];
179
+ interpolateUrl(e, t) {
180
+ return e.replace(/{([^}]+?)}/g, (s, n) => {
181
+ if (!(n in t))
182
+ throw new Error(`Missing required URL parameter: ${n}`);
183
+ return t[n];
144
184
  });
145
185
  }
146
- async query(e, s) {
186
+ async queryRaw(e, t) {
147
187
  try {
148
- const { method: n, url: r } = this.parseOperation(e), a = this.interpolateUrl(r, (s == null ? void 0 : s.params) ?? {}), i = await fetch(`${this.options.baseURL}/store-api${a}`, {
149
- ...s,
150
- method: n,
188
+ const { method: s, url: n } = this.parseOperation(e), a = this.interpolateUrl(n, (t == null ? void 0 : t.params) ?? {}), h = t != null && t.query ? `?${b(t.query)}` : "", c = await fetch(`${this.options.baseURL}/store-api${a}${h}`, {
189
+ ...t,
190
+ method: s,
151
191
  headers: {
152
192
  "Content-Type": "application/json",
153
193
  "sw-access-key": this.options.apiKey,
154
194
  ...this.options.contextToken && { "sw-context-token": this.options.contextToken },
155
195
  ...this.options.includeSeoUrls && { "sw-include-seo-urls": "true" },
156
196
  ...this.options.language && { "sw-language-id": this.options.language },
157
- ...s == null ? void 0 : s.headers
197
+ ...t == null ? void 0 : t.headers
158
198
  },
159
- body: s != null && s.body ? JSON.stringify(s.body) : void 0
199
+ body: t != null && t.body ? JSON.stringify(t.body) : void 0
160
200
  });
161
- if (!i.ok)
162
- throw new h(
163
- `Shopware API request failed: ${i.statusText}`,
164
- i.status,
165
- await i.json().catch(() => {
201
+ if (!c.ok) {
202
+ const l = new p(
203
+ `Shopware API request failed: ${c.statusText}`,
204
+ c.status,
205
+ await c.json().catch(() => {
166
206
  })
167
207
  );
208
+ throw this.emit("error", l), l;
209
+ }
168
210
  if (this.options.reflectContextToken) {
169
- const l = i.headers.get("sw-context-token");
170
- l && (this.setContextToken(l), this.emit("contextToken", l));
211
+ const l = c.headers.get("sw-context-token");
212
+ l && this.setContextToken(l);
171
213
  }
172
- return await i.json();
173
- } catch (n) {
174
- throw n instanceof h ? n : new h(
214
+ return c;
215
+ } catch (s) {
216
+ throw s instanceof p ? s : new p(
175
217
  "Failed to communicate with Shopware API",
176
218
  500,
177
- n instanceof Error ? n.message : void 0
219
+ s instanceof Error ? s.message : void 0
178
220
  );
179
221
  }
180
222
  }
223
+ async query(e, t) {
224
+ return (await this.queryRaw(e, t)).json();
225
+ }
181
226
  }
182
227
  export {
183
- h as ShopwareApiError,
228
+ p as ShopwareApiError,
184
229
  v as ShopwareClient
185
230
  };
@@ -0,0 +1 @@
1
+ export declare function createQueryParams(params: Record<string, unknown>): URLSearchParams;
package/dist/types.d.ts CHANGED
@@ -16,7 +16,9 @@ export type OperationOptions<Operations, K extends OperationKey<Operations>> = O
16
16
  params?: void;
17
17
  } : {
18
18
  params: T;
19
- }) : never);
19
+ }) : never) & {
20
+ query?: Record<string, unknown>;
21
+ };
20
22
  export interface ShopwareClientOptions {
21
23
  baseURL: string;
22
24
  apiKey: string;
package/docs/index.md ADDED
@@ -0,0 +1,161 @@
1
+ # Shopware API Client
2
+
3
+ A TypeScript client for the Shopware Store API with full type safety and event-driven context management.
4
+
5
+ Install with `npm i @teamnovu/kit-shopware-api-client`
6
+
7
+ ## Features
8
+
9
+ - ✅ **Type-safe API calls** - Full TypeScript support with operation-based type inference
10
+ - ✅ **Automatic context token management** - Handles authentication tokens automatically
11
+ - ✅ **Event-driven architecture** - Subscribe to context token changes
12
+ - ✅ **URL parameter interpolation** - Dynamic URL path parameters with type safety
13
+ - ✅ **Query parameter support** - Type-safe query string generation
14
+ - ✅ **SEO URLs support** - Optional SEO-friendly URL responses
15
+ - ✅ **Error handling** - Custom error types with response details
16
+
17
+ ## Basic Usage
18
+
19
+ ```typescript
20
+ import { ShopwareClient } from '@teamnovu/kit-shopware-api-client'
21
+
22
+ // Initialize the client
23
+ const client = new ShopwareClient({
24
+ baseURL: 'https://your-shopware-store.com',
25
+ apiKey: 'your-api-key',
26
+ includeSeoUrls: true,
27
+ language: 'language-id' // optional
28
+ })
29
+
30
+ // Make API calls using operation strings
31
+ const products = await client.query('readProductListing post /product-listing', {
32
+ body: {
33
+ // request body
34
+ }
35
+ })
36
+
37
+ // With URL parameters
38
+ const product = await client.query('readProduct post /product/{productId}', {
39
+ params: {
40
+ productId: 'product-uuid'
41
+ }
42
+ })
43
+
44
+ // With query parameters
45
+ const categories = await client.query('readCategoryList post /category', {
46
+ query: {
47
+ limit: 10,
48
+ page: 1
49
+ }
50
+ })
51
+ ```
52
+
53
+ ## Client Configuration
54
+
55
+ ### ShopwareClientOptions
56
+
57
+ | Option | Type | Required | Default | Description |
58
+ |--------|------|----------|---------|-------------|
59
+ | `baseURL` | `string` | ✅ | - | The base URL of your Shopware store |
60
+ | `apiKey` | `string` | ✅ | - | Your Shopware Store API access key |
61
+ | `language` | `string` | ❌ | `undefined` | Language ID for localized responses |
62
+ | `contextToken` | `string` | ❌ | `undefined` | Initial context token for authenticated requests |
63
+ | `includeSeoUrls` | `boolean` | ❌ | `false` | Include SEO-friendly URLs in responses |
64
+ | `reflectContextToken` | `boolean` | ❌ | `true` | Automatically update context token from responses |
65
+
66
+ ## Operation Format
67
+
68
+ Operations follow the pattern: `{operationName} {httpMethod} {urlPath}`
69
+
70
+ Examples:
71
+ - `'readProductListing post /product-listing'`
72
+ - `'readProduct post /product/{productId}'`
73
+ - `'addLineItem patch /checkout/cart/line-item'`
74
+
75
+ ## Context Token Management
76
+
77
+ The client automatically manages context tokens for session handling:
78
+
79
+ ```typescript
80
+ // Listen for context token changes
81
+ client.on('contextToken', (token) => {
82
+ console.log('New context token:', token)
83
+ // Store token for future requests
84
+ })
85
+
86
+ // Manually set context token
87
+ client.setContextToken('your-context-token')
88
+ ```
89
+
90
+ ## Error Handling
91
+
92
+ The client throws `ShopwareApiError` for API failures:
93
+
94
+ ```typescript
95
+ import { ShopwareApiError } from '@teamnovu/kit-shopware-api-client'
96
+
97
+ try {
98
+ const result = await client.query('someOperation post /some-endpoint')
99
+ } catch (error) {
100
+ if (error instanceof ShopwareApiError) {
101
+ console.error('API Error:', error.message)
102
+ console.error('Status:', error.status)
103
+ console.error('Response:', error.response)
104
+ }
105
+ }
106
+ ```
107
+
108
+ ## Advanced Usage
109
+
110
+ ### Raw Response Access
111
+
112
+ Use `queryRaw()` to access the raw fetch Response:
113
+
114
+ ```typescript
115
+ const response = await client.queryRaw('readProduct post /product/{productId}', {
116
+ params: { productId: 'uuid' }
117
+ })
118
+
119
+ const data = await response.json()
120
+ const headers = response.headers
121
+ ```
122
+
123
+ ### Dynamic Configuration
124
+
125
+ Update client configuration at runtime:
126
+
127
+ ```typescript
128
+ client.setBaseURL('https://new-store.com')
129
+ client.setApiKey('new-api-key')
130
+ client.setLanguage('new-language-id')
131
+ client.setIncludeSeoUrls(true)
132
+ client.setReflectContextToken(false)
133
+ ```
134
+
135
+ ## Type Safety
136
+
137
+ The client provides full TypeScript support when used with generated operation types:
138
+
139
+ ```typescript
140
+ type MyOperations = {
141
+ 'readProduct post /product/{productId}': {
142
+ body?: { includes?: Record<string, any> }
143
+ response: ProductDetailResponse
144
+ }
145
+ 'readProductListing post /product-listing': {
146
+ body: ProductListingCriteria
147
+ response: ProductListingResponse
148
+ }
149
+ }
150
+
151
+ const client = new ShopwareClient<MyOperations>({
152
+ baseURL: 'https://store.com',
153
+ apiKey: 'key'
154
+ })
155
+
156
+ // Now fully type-safe!
157
+ const product = await client.query('readProduct post /product/{productId}', {
158
+ params: { productId: 'uuid' } // TypeScript enforces this
159
+ })
160
+ // product is typed as ProductDetailResponse
161
+ ```
package/docs/info.json ADDED
@@ -0,0 +1,3 @@
1
+ {
2
+ "name": "🛒 Shopware API Client"
3
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamnovu/kit-shopware-api-client",
3
- "version": "0.0.3",
3
+ "version": "0.0.4",
4
4
  "description": "A client for the Shopware API",
5
5
  "main": "dist/index.mjs",
6
6
  "module": "dist/index.mjs",
@@ -21,6 +21,9 @@
21
21
  "keywords": [],
22
22
  "author": "Elias Bernhaut",
23
23
  "homepage": "https://kit.novu.ch/packages/shopware-api-client/",
24
+ "dependencies": {
25
+ "zod": "^3.25.67"
26
+ },
24
27
  "scripts": {
25
28
  "build": "vite build",
26
29
  "watch": "NODE_ENV=development vite build --watch",
package/src/client.ts CHANGED
@@ -1,27 +1,25 @@
1
+ import { ShopwareApiError } from './error'
1
2
  import { EventEmitter } from './eventEmitter'
3
+ import { createQueryParams } from './query'
2
4
  import type {
3
5
  OperationOptions,
4
6
  OperationProp,
5
7
  ShopwareClientOptions,
6
8
  } from './types'
7
9
 
8
- export class ShopwareApiError extends Error {
9
- constructor(
10
- message: string,
11
- public readonly status: number,
12
- public readonly response?: unknown,
13
- ) {
14
- super(message)
15
- this.name = 'ShopwareApiError'
16
- }
10
+ const operationRegex = /^(?<name>\w+?)\s(?<method>get|post|put|patch|delete)\s+(?<url>\/.*)/i
11
+
12
+ // This **Must** stay an interface and the response **must** be branded.
13
+ // This is to ensure that the response type is not already resolved when the
14
+ // library is built so we can still use module augmentation to override operations.
15
+ export interface ResponseType<TKey> {
16
+ __response: TKey
17
17
  }
18
18
 
19
- const operationRegex = /^(?<name>\w+?)\s(?<method>get|post|put|patch|delete)\s+(?<url>\/.*)/i
19
+ export type BrandedResponse<Operations, OperationKey extends (keyof Operations) & string> =
20
+ ResponseType<OperationKey> & OperationProp<Operations, OperationKey, 'response'>
20
21
 
21
- export class ShopwareClient<Operations extends Record<string, {
22
- body?: unknown
23
- response?: unknown
24
- }>> extends EventEmitter {
22
+ export class ShopwareClient<Operations> extends EventEmitter {
25
23
  private options: ShopwareClientOptions = {
26
24
  baseURL: '',
27
25
  apiKey: '',
@@ -72,6 +70,7 @@ export class ShopwareClient<Operations extends Record<string, {
72
70
  }
73
71
 
74
72
  this.options.contextToken = contextToken
73
+ this.emit('contextToken', contextToken)
75
74
  }
76
75
 
77
76
  public setIncludeSeoUrls(includeSeoUrls: boolean = true) {
@@ -107,16 +106,18 @@ export class ShopwareClient<Operations extends Record<string, {
107
106
  })
108
107
  }
109
108
 
110
- async query<OperationKey extends (keyof Operations) & string>(
109
+ async queryRaw<OperationKey extends (keyof Operations) & string>(
111
110
  operation: OperationKey,
112
111
  options?: OperationOptions<Operations, OperationKey>,
113
- ): Promise<OperationProp<Operations, OperationKey, 'response'>> {
112
+ ): Promise<Response> {
114
113
  try {
115
114
  const { method, url } = this.parseOperation(operation)
116
115
 
117
116
  const interpolatedUrl = this.interpolateUrl(url, options?.params ?? {})
118
117
 
119
- const response = await fetch(`${this.options.baseURL}/store-api${interpolatedUrl}`, {
118
+ const query = options?.query ? `?${createQueryParams(options.query)}` : ''
119
+
120
+ const response = await fetch(`${this.options.baseURL}/store-api${interpolatedUrl}${query}`, {
120
121
  ...options,
121
122
  method,
122
123
  headers: {
@@ -131,23 +132,25 @@ export class ShopwareClient<Operations extends Record<string, {
131
132
  })
132
133
 
133
134
  if (!response.ok) {
134
- throw new ShopwareApiError(
135
+ const error = new ShopwareApiError(
135
136
  `Shopware API request failed: ${response.statusText}`,
136
137
  response.status,
137
138
  await response.json().catch(() => undefined),
138
139
  )
140
+
141
+ this.emit('error', error)
142
+
143
+ throw error
139
144
  }
140
145
 
141
146
  if (this.options.reflectContextToken) {
142
147
  const contextToken = response.headers.get('sw-context-token')
143
148
  if (contextToken) {
144
149
  this.setContextToken(contextToken)
145
- this.emit('contextToken', contextToken)
146
150
  }
147
151
  }
148
152
 
149
- const data = await response.json()
150
- return data
153
+ return response
151
154
  } catch (error) {
152
155
  if (error instanceof ShopwareApiError) {
153
156
  throw error
@@ -160,4 +163,13 @@ export class ShopwareClient<Operations extends Record<string, {
160
163
  )
161
164
  }
162
165
  }
166
+
167
+ async query<OperationKey extends (keyof Operations) & string>(
168
+ operation: OperationKey,
169
+ options?: OperationOptions<Operations, OperationKey>,
170
+ ): Promise<BrandedResponse<Operations, OperationKey>> {
171
+ const response = await this.queryRaw(operation, options)
172
+
173
+ return response.json()
174
+ }
163
175
  }
package/src/error.ts ADDED
@@ -0,0 +1,42 @@
1
+ import { z } from 'zod'
2
+
3
+ const shopwareErrorSchema = z.object({
4
+ status: z.string(),
5
+ code: z.string(),
6
+ title: z.string().optional(),
7
+ detail: z.string().optional(),
8
+ meta: z.record(z.unknown()).optional(),
9
+ source: z.object({
10
+ pointer: z.string().optional(),
11
+ }).optional(),
12
+ trace: z.array(
13
+ z.object({
14
+ file: z.string(),
15
+ line: z.number(),
16
+ function: z.string(),
17
+ }),
18
+ ).optional(),
19
+ })
20
+
21
+ const shopwareErrorResponseSchema = z.object({
22
+ errors: z.array(shopwareErrorSchema),
23
+ })
24
+
25
+ export type ShopwareError = z.infer<typeof shopwareErrorSchema>
26
+
27
+ export class ShopwareApiError extends Error {
28
+ errors: ShopwareError[]
29
+
30
+ constructor(
31
+ message: string,
32
+ public readonly status: number,
33
+ public readonly response?: unknown,
34
+ ) {
35
+ super(message)
36
+ this.name = 'ShopwareApiError'
37
+
38
+ const { success, data } = shopwareErrorResponseSchema.safeParse(response)
39
+
40
+ this.errors = success ? data.errors : []
41
+ }
42
+ }
package/src/index.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './client'
2
2
  export * from './types'
3
+ export { type ShopwareError, ShopwareApiError } from './error'
package/src/query.ts ADDED
@@ -0,0 +1,39 @@
1
+ const isIgnored = (value: unknown) =>
2
+ value === undefined
3
+ || value === null
4
+ || (typeof value === 'number' && isNaN(value as number))
5
+ || typeof value === 'function'
6
+
7
+ export function createQueryParams(params: Record<string, unknown>) {
8
+ const queryParams = new URLSearchParams()
9
+
10
+ const appendNested = (key: string, value: unknown) => {
11
+ if (isIgnored(value)) {
12
+ return
13
+ }
14
+
15
+ if (typeof value === 'object') {
16
+ queryParams.append(key, JSON.stringify(value))
17
+ }
18
+
19
+ queryParams.append(key, String(value))
20
+ }
21
+
22
+ for (const [key, value] of Object.entries(params)) {
23
+ if (isIgnored(value)) {
24
+ continue
25
+ }
26
+
27
+ if (typeof value === 'string') {
28
+ queryParams.append(key, String(value))
29
+ } else if (Array.isArray(value)) {
30
+ for (const item of value) {
31
+ appendNested(`${key}[]`, item)
32
+ }
33
+ } else {
34
+ appendNested(key, value)
35
+ }
36
+ }
37
+
38
+ return queryParams
39
+ }
package/src/types.ts CHANGED
@@ -33,6 +33,9 @@ export type OperationOptions<
33
33
  (UrlParamsRecord<ExtractUrlFromOperation<K>> extends infer T
34
34
  ? (keyof T extends never ? { params?: void } : { params: T })
35
35
  : never)
36
+ & {
37
+ query?: Record<string, unknown>
38
+ }
36
39
 
37
40
  export interface ShopwareClientOptions {
38
41
  baseURL: string