-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.ts
More file actions
293 lines (254 loc) · 7.71 KB
/
api.ts
File metadata and controls
293 lines (254 loc) · 7.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import {
IAddItemToCartData,
IAddItemToCartReply,
IECommerceApiActions,
IGetParentPageInfoReply,
IGetUserProfileReply,
IMessageToParentReply,
IScrollingApiLoadMoreReply,
IScrollingApiSetParametersReply,
IUpdateSharingLinkData,
IUpdateSharingLinkReply,
} from "@AppBuilderShared/modules/ecommerce/types/ecommerceapi";
import {QUERYPARAM_MODELSTATEID} from "@AppBuilderShared/types/shapediver/queryparams";
import {
IWordpressApi,
IWordpressApiOptions,
IWordPressECommerceApiActionsOptions,
} from "./types/api";
import {
IWordpressAddToCartRequest,
IWordpressGetProductDataRequest,
WordPressAjaxRequestType,
} from "./types/request";
import {
IWordpressAddToCartResponse,
IWordpressGetCartResponse,
IWordpressGetProductDataResponse,
IWordpressGetUserProfileResponse,
} from "./types/response";
import {
IWordpressAddToCartResponseSchema,
IWordpressGetCartResponseSchema,
IWordpressGetProductDataResponseSchema,
IWordpressGetUserProfileResponseSchema,
} from "./types/responsetypecheck";
interface IWordPressAjaxResponse<T> {
success: boolean;
data?: T;
}
export class WordpressApi implements IWordpressApi {
private ajaxurl: string;
private debug: boolean;
constructor(options: IWordpressApiOptions) {
this.ajaxurl = options.ajaxUrl;
this.debug = options.debug ?? false;
}
async request<Trequest extends WordPressAjaxRequestType, Tresponse>(
method: string,
action: string,
request: Trequest extends any[] ? never : Trequest,
): Promise<Tresponse> {
// transform request object: any property that is not a primitive must be JSON stringified
const _request: WordPressAjaxRequestType = {};
for (const key in request) {
if (key === "action")
throw new Error(
"The request object cannot contain a property named 'action'",
);
const value = request[key];
if (typeof value === "object" && value !== null) {
_request[key] = JSON.stringify(value);
} else if (value !== undefined) {
_request[key] = value;
}
}
const response = await fetch(this.ajaxurl, {
method,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
// CAUTION: This can easily lead to trouble if the request object
// includes a property named "action". Therefore checking for this above.
action,
..._request,
}),
});
// Handle 4XX or 5XX HTTP statuses
if (!response.ok) {
const errorResponse = await response.json();
const msg = `WordpressApiError: ${response.status} ${response.statusText} ${errorResponse}`;
this.log(msg);
throw new Error(msg);
}
// TODO validate response using a zod schema
const ajaxResponse =
(await response.json()) as IWordPressAjaxResponse<Tresponse>;
if (!ajaxResponse.success) {
const msg = `WordpressApiError: ${JSON.stringify(ajaxResponse, null, 0)}`;
this.log(msg);
throw new Error(msg);
}
if (!ajaxResponse.data) {
const msg = `WordpressApiError: No data: ${JSON.stringify(ajaxResponse, null, 0)}`;
this.log(msg);
throw new Error(msg);
}
return ajaxResponse.data as Tresponse;
}
log(...message: any[]): void {
if (this.debug)
console.log(
`WordpressApi (ajaxurl = "${this.ajaxurl}"):`,
...message,
);
}
async getProductData(
id: number,
): Promise<IWordpressGetProductDataResponse> {
const data = await this.request<
IWordpressGetProductDataRequest,
IWordpressGetProductDataResponse
>("POST", "get_product_data", {product_id: id});
return IWordpressGetProductDataResponseSchema.parse(data);
}
async getUserProfile(): Promise<IWordpressGetUserProfileResponse> {
const data = await this.request<
WordPressAjaxRequestType,
IWordpressGetUserProfileResponse
>("POST", "get_user_profile", {});
return IWordpressGetUserProfileResponseSchema.parse(data);
}
async getCart(): Promise<IWordpressGetCartResponse> {
const data = await this.request<
WordPressAjaxRequestType,
IWordpressGetCartResponse
>("POST", "get_cart", {});
return IWordpressGetCartResponseSchema.parse(data);
}
async addToCart(
request: IWordpressAddToCartRequest,
): Promise<IWordpressAddToCartResponse> {
const data = await this.request<
IWordpressAddToCartRequest,
IWordpressAddToCartResponse
>("POST", "add_to_cart", request);
// Trigger WooCommerce cart refresh
// see https://developer.woocommerce.com/docs/block-development/getting-started/faq/#how-to-force-refresh-the-cart-from-the-server
try {
if ((globalThis as any).wp?.data?.dispatch) {
(globalThis as any).wp.data
.dispatch("wc/store/cart")
.invalidateResolutionForStore("cart");
} else {
(globalThis as any)
.jQuery(document.body)
.trigger("wc_fragment_refresh");
}
} catch (e) {
console.log("Could not trigger WooCommerce cart refresh", e);
}
return IWordpressAddToCartResponseSchema.parse(data);
}
}
/**
* Implementation of the e-commerce API actions for WordPress.
*/
export class WordPressECommerceApiActions implements IECommerceApiActions {
private wordpressApi: IWordpressApi;
private options: IWordPressECommerceApiActionsOptions;
private debug: boolean;
constructor(
wordpressApi: IWordpressApi,
options: IWordPressECommerceApiActionsOptions,
) {
this.wordpressApi = wordpressApi;
this.options = options;
this.debug = options.debug ?? false;
}
async scrollingApiSetParameters() /*data: IScrollingApiSetParametersData,*/
: Promise<IScrollingApiSetParametersReply<unknown>> {
return {hasNextPage: false, items: []};
}
async scrollingApiLoadMore() /*data: IScrollingApiLoadMoreData,*/
: Promise<IScrollingApiLoadMoreReply<unknown>> {
return {hasNextPage: false, items: []};
}
updateSharingLink(
data: IUpdateSharingLinkData,
): Promise<IUpdateSharingLinkReply> {
const {modelStateId} = data;
const url = new URL(window.location.href);
url.searchParams.set(QUERYPARAM_MODELSTATEID, modelStateId);
const href = url.toString();
history.replaceState(history.state, "", href);
return Promise.resolve({href});
}
async closeConfigurator(): Promise<boolean> {
if (this.options.closeConfiguratorHandler) {
return await this.options.closeConfiguratorHandler();
}
return false;
}
log(...message: any[]): void {
if (this.debug)
console.log(
`WordPressECommerceApiActions (options = "${this.options}"):`,
...message,
);
}
async addItemToCart(
data: IAddItemToCartData,
): Promise<IAddItemToCartReply> {
let product_id: number = this.options.productId;
if (data.productId) {
try {
product_id = parseInt(data.productId);
} catch (e) {
throw new Error(
`Could not parse productId "${data.productId}" to an integer: ${e}`,
);
}
}
// map request
const request: IWordpressAddToCartRequest = {
product_id,
quantity: data.quantity,
custom_price: data.price,
custom_data: {
model_state_id: data.modelStateId,
// TODO Juan please implement to use the description when displaying the cart
description: data.description,
},
};
const result = await this.wordpressApi.addToCart(request);
// map response
// The ajax handler returns an object without a cart_item_key property in case of error.
if (
typeof result.cart_item_key !== "string" ||
result.cart_item_key.length === 0
) {
throw new Error(result.message ?? "Unknown error");
}
return {
id: result.cart_item_key,
};
}
async getUserProfile(): Promise<IGetUserProfileReply> {
const result = await this.wordpressApi.getUserProfile();
// map response
return {
id: result.id + "",
email: result.email,
name: result.name,
};
}
async getParentPageInfo(): Promise<IGetParentPageInfoReply> {
return Promise.resolve({href: window.location.href});
}
messageToParent() /*data: IMessageToParentData,*/
: Promise<IMessageToParentReply> {
return Promise.resolve({});
}
}