@shopware/api-client 0.2.1 → 0.4.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.
@@ -0,0 +1 @@
1
+ export * from "./apiTypes-6.5.3.0";
package/dist/index.cjs ADDED
@@ -0,0 +1,242 @@
1
+ 'use strict';
2
+
3
+ const ofetch = require('ofetch');
4
+
5
+ var __defProp = Object.defineProperty;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __publicField = (obj, key, value) => {
8
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
9
+ return value;
10
+ };
11
+ class ApiClientError extends Error {
12
+ constructor(response) {
13
+ let message = "Failed request";
14
+ message += response._data?.errors.reduce((message2, error) => {
15
+ let pointer = "";
16
+ if (error.source?.pointer) {
17
+ pointer = `[${error.source.pointer}]`;
18
+ }
19
+ return `${message2}
20
+ - [${error.title}]${pointer} ${error.detail ?? ""}`;
21
+ }, "");
22
+ super(message);
23
+ /**
24
+ * Flag to indicate if the request was successful.
25
+ */
26
+ __publicField(this, "ok");
27
+ /**
28
+ * HTTP status code of the response.
29
+ */
30
+ __publicField(this, "status");
31
+ /**
32
+ * HTTP status text of the response.
33
+ */
34
+ __publicField(this, "statusText");
35
+ /**
36
+ * URL of the request.
37
+ */
38
+ __publicField(this, "url");
39
+ /**
40
+ * Details of the error.
41
+ */
42
+ __publicField(this, "details");
43
+ /**
44
+ * Headers of the response.
45
+ */
46
+ __publicField(this, "headers");
47
+ this.name = "ApiClientError";
48
+ this.details = response._data || {
49
+ errors: [{ title: "Unknown error", detail: "" }]
50
+ };
51
+ this.ok = response.ok;
52
+ this.status = response.status;
53
+ this.statusText = response.statusText;
54
+ this.url = response.url;
55
+ this.headers = response.headers;
56
+ }
57
+ }
58
+ function errorInterceptor(response) {
59
+ throw new ApiClientError(response);
60
+ }
61
+
62
+ function transformPathToQuery(path, params) {
63
+ const [, method, pathDefinition, headerParams] = path.split(" ");
64
+ const [requestPath, queryParams] = pathDefinition.split("?");
65
+ const pathParams = requestPath.match(/{[^}]+}/g)?.map((param) => param.substring(1, param.length - 1)) || [];
66
+ const requestPathWithParams = pathParams.reduce((acc, paramName) => {
67
+ return acc.replace(`{${paramName}}`, params[paramName]);
68
+ }, requestPath);
69
+ const queryParamNames = queryParams?.split(",") || [];
70
+ const headerParamnames = headerParams?.split(",") || [];
71
+ const headers = {};
72
+ headerParamnames.forEach((paramName) => {
73
+ headers[paramName] = params[paramName];
74
+ });
75
+ const query = {};
76
+ queryParamNames.forEach((paramName) => {
77
+ let queryParamName = paramName;
78
+ if (Array.isArray(params[paramName]) && !queryParamName.includes("[]")) {
79
+ queryParamName += "[]";
80
+ }
81
+ query[queryParamName] = params[paramName];
82
+ });
83
+ const returnOptions = {
84
+ method: method.toUpperCase(),
85
+ headers,
86
+ query
87
+ };
88
+ Object.keys(params).forEach((key) => {
89
+ if (!pathParams.includes(key) && !queryParamNames.includes(key) && !headerParamnames.includes(key)) {
90
+ returnOptions.body ?? (returnOptions.body = {});
91
+ Reflect.set(returnOptions.body, key, params[key]);
92
+ }
93
+ });
94
+ return [requestPathWithParams, returnOptions];
95
+ }
96
+
97
+ function createAPIClient(params) {
98
+ const defaultHeaders = {
99
+ "sw-access-key": params.accessToken
100
+ };
101
+ if (params.contextToken) {
102
+ defaultHeaders["sw-context-token"] = params.contextToken;
103
+ }
104
+ const apiFetch = ofetch.ofetch.create({
105
+ baseURL: params.baseURL,
106
+ // async onRequest({ request, options }) {},
107
+ // async onRequestError({ request, options, error }) {},
108
+ async onResponse(context) {
109
+ if (defaultHeaders["sw-context-token"] !== context.response.headers.get("sw-context-token")) {
110
+ const newContextToken = context.response.headers.get("sw-context-token") || "";
111
+ defaultHeaders["sw-context-token"] = newContextToken;
112
+ params.onContextChanged?.(newContextToken);
113
+ }
114
+ },
115
+ async onResponseError({ request, response, options }) {
116
+ errorInterceptor(response);
117
+ }
118
+ });
119
+ async function invoke(pathParam, params2) {
120
+ const [requestPath, options] = transformPathToQuery(
121
+ pathParam,
122
+ params2
123
+ );
124
+ return apiFetch(
125
+ requestPath,
126
+ {
127
+ ...options,
128
+ headers: {
129
+ ...defaultHeaders,
130
+ ...options.headers
131
+ }
132
+ }
133
+ );
134
+ }
135
+ return {
136
+ invoke
137
+ };
138
+ }
139
+ function createAuthorizationHeader(token) {
140
+ if (!token)
141
+ return null;
142
+ if (token.startsWith("Bearer "))
143
+ return token;
144
+ return `Bearer ${token}`;
145
+ }
146
+ function createAdminAPIClient(params) {
147
+ const sessionData = {
148
+ accessToken: params.sessionData?.accessToken || "",
149
+ refreshToken: params.sessionData?.refreshToken || "",
150
+ expirationTime: Number(params.sessionData?.expirationTime || 0)
151
+ };
152
+ function updateSessionData(responseData) {
153
+ if (responseData?.access_token) {
154
+ defaultHeaders.Authorization = createAuthorizationHeader(
155
+ responseData.access_token
156
+ );
157
+ sessionData.accessToken = responseData.access_token;
158
+ sessionData.refreshToken = responseData.refresh_token;
159
+ sessionData.expirationTime = Date.now() + responseData.expires_in * 1e3;
160
+ params.onAuthChange?.({
161
+ ...sessionData
162
+ });
163
+ }
164
+ }
165
+ function setSessionData(data) {
166
+ sessionData.accessToken = data.accessToken;
167
+ sessionData.refreshToken = data.refreshToken;
168
+ sessionData.expirationTime = data.expirationTime;
169
+ return getSessionData();
170
+ }
171
+ function getSessionData() {
172
+ return { ...sessionData };
173
+ }
174
+ const defaultHeaders = {
175
+ Authorization: createAuthorizationHeader(sessionData.accessToken)
176
+ };
177
+ const apiFetch = ofetch.ofetch.create({
178
+ baseURL: params.baseURL,
179
+ async onRequest({ request, options }) {
180
+ const isExpired = sessionData.expirationTime <= Date.now();
181
+ if (isExpired && !request.toString().includes("/oauth/token")) {
182
+ await ofetch.ofetch("/oauth/token", {
183
+ baseURL: params.baseURL,
184
+ method: "POST",
185
+ body: {
186
+ grant_type: "refresh_token",
187
+ client_id: "administration",
188
+ refresh_token: sessionData.refreshToken || ""
189
+ },
190
+ headers: defaultHeaders,
191
+ onResponseError({ response }) {
192
+ errorInterceptor(response);
193
+ },
194
+ onResponse(context) {
195
+ updateSessionData(context.response._data);
196
+ }
197
+ });
198
+ }
199
+ },
200
+ async onResponse(context) {
201
+ updateSessionData(context.response._data);
202
+ },
203
+ async onResponseError({ request, response, options }) {
204
+ errorInterceptor(response);
205
+ }
206
+ });
207
+ async function invoke(pathParam, params2) {
208
+ const [requestPath, options] = transformPathToQuery(
209
+ pathParam,
210
+ params2
211
+ );
212
+ return apiFetch(
213
+ requestPath,
214
+ {
215
+ ...options,
216
+ headers: {
217
+ ...defaultHeaders,
218
+ ...options.headers
219
+ }
220
+ }
221
+ );
222
+ }
223
+ return {
224
+ /**
225
+ * Invoke API request based on provided path definition.
226
+ */
227
+ invoke,
228
+ /**
229
+ * Enables to change session data in runtime. Useful for testing purposes.
230
+ * Setting session data with this methis will **not** fire `onAuthChange` hook.
231
+ */
232
+ setSessionData,
233
+ /**
234
+ * Returns current session data. Useful for testing purposes, as in most cases you'll want to use `onAuthChange` hook for that.
235
+ */
236
+ getSessionData
237
+ };
238
+ }
239
+
240
+ exports.ApiClientError = ApiClientError;
241
+ exports.createAPIClient = createAPIClient;
242
+ exports.createAdminAPIClient = createAdminAPIClient;