/
shopifytools.ts
84 lines (80 loc) · 2.44 KB
/
shopifytools.ts
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
namespace gdjs {
export interface RuntimeGame {
shopifyClients: { [name: string]: any };
}
declare var ShopifyBuy: any;
export class ShopifyClientsManager {
static set(
instanceContainer: gdjs.RuntimeInstanceContainer,
name: string,
shopifyClient
) {
const game = instanceContainer.getGame();
if (!game.shopifyClients) {
game.shopifyClients = {};
}
game.shopifyClients[name] = shopifyClient;
}
static get(instanceContainer: gdjs.RuntimeInstanceContainer, name: string) {
const game = instanceContainer.getGame();
if (!game.shopifyClients) {
game.shopifyClients = {};
}
return game.shopifyClients[name];
}
}
export namespace evtTools {
export namespace shopify {
export const buildClient = function (
instanceContainer: gdjs.RuntimeInstanceContainer,
name: string,
domain: string,
appId: string,
accessToken: string
) {
if (typeof ShopifyBuy === 'undefined') {
return;
}
const config = new ShopifyBuy.Config({
accessToken: accessToken,
domain: domain,
appId: appId,
});
const shopifyClient = ShopifyBuy.buildClient(config);
ShopifyClientsManager.set(instanceContainer, name, shopifyClient);
};
export const getCheckoutUrlForProduct = function (
instanceContainer: gdjs.RuntimeInstanceContainer,
name: string,
productId: string,
quantity: number,
variantIndex: number,
successVariable: gdjs.Variable,
errorVariable: gdjs.Variable
) {
errorVariable.setString('');
successVariable.setString('');
const shopifyClient = ShopifyClientsManager.get(
instanceContainer,
name
);
shopifyClient.fetchProduct(productId).then(
function (product) {
if (variantIndex < 0 || variantIndex >= product.variants.length) {
errorVariable.setString('The product has no variant.');
return;
}
const variant = product.variants[variantIndex];
const checkoutURL = variant.checkoutUrl(quantity);
successVariable.setString(checkoutURL);
},
function (error) {
errorVariable.setString(
'Unable to get the product that was requested.'
);
}
);
};
}
}
}