@teamnovu/kit-shopware-api-client 0.0.3 → 0.0.5
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 +6 -9
- package/dist/error.d.ts +64 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.mjs +128 -83
- package/dist/query.d.ts +1 -0
- package/dist/types.d.ts +3 -1
- package/docs/index.md +161 -0
- package/docs/info.json +3 -0
- package/package.json +4 -1
- package/src/client.ts +33 -21
- package/src/error.ts +42 -0
- package/src/index.ts +1 -0
- package/src/query.ts +39 -0
- package/src/types.ts +3 -0
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
|
|
4
|
-
|
|
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
|
|
9
|
-
|
|
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
|
-
|
|
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
|
}
|
package/dist/error.d.ts
ADDED
|
@@ -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
package/dist/index.mjs
CHANGED
|
@@ -1,96 +1,136 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
3
|
-
var
|
|
4
|
-
|
|
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
|
-
|
|
35
|
+
u(this, "listeners", /* @__PURE__ */ new Map());
|
|
7
36
|
}
|
|
8
|
-
addEventListener(
|
|
37
|
+
addEventListener(r, e, t) {
|
|
9
38
|
if (!e) return;
|
|
10
|
-
const
|
|
39
|
+
const s = this.normalizeOptions(t), n = {
|
|
11
40
|
listener: e,
|
|
12
|
-
options:
|
|
41
|
+
options: s
|
|
13
42
|
};
|
|
14
|
-
if (
|
|
15
|
-
if (
|
|
16
|
-
|
|
17
|
-
this.removeEventListener(
|
|
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(
|
|
49
|
+
this.listeners.has(r) || this.listeners.set(r, []), this.listeners.get(r).push(n);
|
|
21
50
|
}
|
|
22
|
-
removeEventListener(
|
|
51
|
+
removeEventListener(r, e, t) {
|
|
23
52
|
if (!e) return;
|
|
24
|
-
const
|
|
25
|
-
if (!
|
|
26
|
-
const
|
|
27
|
-
a !== -1 && (
|
|
28
|
-
}
|
|
29
|
-
dispatchEvent(
|
|
30
|
-
var
|
|
31
|
-
const e = this.listeners.get(
|
|
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
|
|
34
|
-
for (const
|
|
35
|
-
if (!((
|
|
62
|
+
const t = [...e];
|
|
63
|
+
for (const n of t)
|
|
64
|
+
if (!((s = n.signal) != null && s.aborted)) {
|
|
36
65
|
try {
|
|
37
|
-
typeof
|
|
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 (
|
|
70
|
+
if (n.options.once && this.removeEventListener(r.type, n.listener, n.options), r.cancelBubble) break;
|
|
42
71
|
}
|
|
43
|
-
return !
|
|
72
|
+
return !r.defaultPrevented;
|
|
44
73
|
}
|
|
45
|
-
normalizeOptions(
|
|
46
|
-
return typeof
|
|
74
|
+
normalizeOptions(r) {
|
|
75
|
+
return typeof r == "boolean" ? { capture: r } : {
|
|
47
76
|
capture: !1,
|
|
48
77
|
once: !1,
|
|
49
78
|
passive: !1,
|
|
50
|
-
...
|
|
79
|
+
...r
|
|
51
80
|
};
|
|
52
81
|
}
|
|
53
|
-
optionsMatch(
|
|
54
|
-
return
|
|
82
|
+
optionsMatch(r, e) {
|
|
83
|
+
return r.capture === e.capture;
|
|
55
84
|
}
|
|
56
85
|
// Utility methods for easier usage
|
|
57
|
-
on(
|
|
58
|
-
this.addEventListener(
|
|
86
|
+
on(r, e, t) {
|
|
87
|
+
this.addEventListener(r, e, t);
|
|
59
88
|
}
|
|
60
|
-
off(
|
|
61
|
-
this.removeEventListener(
|
|
89
|
+
off(r, e, t) {
|
|
90
|
+
this.removeEventListener(r, e, t);
|
|
62
91
|
}
|
|
63
|
-
once(
|
|
64
|
-
const
|
|
65
|
-
capture:
|
|
92
|
+
once(r, e, t) {
|
|
93
|
+
const s = typeof t == "boolean" ? {
|
|
94
|
+
capture: t,
|
|
66
95
|
once: !0
|
|
67
96
|
} : {
|
|
68
|
-
...
|
|
97
|
+
...t,
|
|
69
98
|
once: !0
|
|
70
99
|
};
|
|
71
|
-
this.addEventListener(
|
|
100
|
+
this.addEventListener(r, e, s);
|
|
72
101
|
}
|
|
73
|
-
emit(
|
|
74
|
-
const
|
|
75
|
-
return this.dispatchEvent(
|
|
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(
|
|
81
|
-
|
|
109
|
+
removeAllListeners(r) {
|
|
110
|
+
r ? this.listeners.delete(r) : this.listeners.clear();
|
|
82
111
|
}
|
|
83
112
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
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
|
|
90
|
-
class v extends
|
|
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
|
-
|
|
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
|
|
131
|
-
if (!(
|
|
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:
|
|
135
|
-
method:
|
|
136
|
-
url:
|
|
174
|
+
name: t.groups.name,
|
|
175
|
+
method: t.groups.method.toUpperCase(),
|
|
176
|
+
url: t.groups.url
|
|
137
177
|
};
|
|
138
178
|
}
|
|
139
|
-
interpolateUrl(e,
|
|
140
|
-
return e.replace(/{([^}]+?)}/g, (
|
|
141
|
-
if (!(
|
|
142
|
-
throw new Error(`Missing required URL parameter: ${
|
|
143
|
-
return
|
|
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
|
|
186
|
+
async queryRaw(e, t) {
|
|
147
187
|
try {
|
|
148
|
-
const { method:
|
|
149
|
-
...
|
|
150
|
-
method:
|
|
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
|
-
...
|
|
197
|
+
...t == null ? void 0 : t.headers
|
|
158
198
|
},
|
|
159
|
-
body:
|
|
199
|
+
body: t != null && t.body ? JSON.stringify(t.body) : void 0
|
|
160
200
|
});
|
|
161
|
-
if (!
|
|
162
|
-
|
|
163
|
-
`Shopware API request failed: ${
|
|
164
|
-
|
|
165
|
-
await
|
|
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 =
|
|
170
|
-
l &&
|
|
211
|
+
const l = c.headers.get("sw-context-token");
|
|
212
|
+
l && this.setContextToken(l);
|
|
171
213
|
}
|
|
172
|
-
return
|
|
173
|
-
} catch (
|
|
174
|
-
throw
|
|
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
|
-
|
|
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
|
-
|
|
228
|
+
p as ShopwareApiError,
|
|
184
229
|
v as ShopwareClient
|
|
185
230
|
};
|
package/dist/query.d.ts
ADDED
|
@@ -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
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@teamnovu/kit-shopware-api-client",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.5",
|
|
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
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
109
|
+
async queryRaw<OperationKey extends (keyof Operations) & string>(
|
|
111
110
|
operation: OperationKey,
|
|
112
111
|
options?: OperationOptions<Operations, OperationKey>,
|
|
113
|
-
): Promise<
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
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
|