-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathcheck-reward.js
More file actions
81 lines (75 loc) · 1.87 KB
/
check-reward.js
File metadata and controls
81 lines (75 loc) · 1.87 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
const { postToHasura } = require('./util/postToHasura');
const {
createShopifyDiscountCode,
} = require('./util/createShopifyDiscountCode');
exports.handler = async (event) => {
const payload = JSON.parse(event.body);
const { new: newAchievement } = payload.event.data;
const { discountCodeBasicCreate } = await createShopifyDiscountCode(
newAchievement.id
);
const { codeDiscountNode: shopifyDiscountCode } = discountCodeBasicCreate;
/**
* Step 1: Check whether achievement meets criteria
* for generating a reward. If not, stop function
* and move on.
*/
if (newAchievement.type !== 'mission-complete') {
return {
statusCode: 200,
body: 'OK! No reward needed!',
};
}
if (!shopifyDiscountCode) {
return {
statusCode: 500,
body: 'Unable to create Shopify reward.',
};
}
/**
* Step 2: Send request to generate reward.
*/
const newReward = await postToHasura({
query: `
mutation AddReward(
$achievement_id: Int!,
$reward_type: String!,
$reward_data: jsonb!
) {
insert_rewards_one(object: {
achievement_id: $achievement_id,
reward_data: $reward_data,
type: $reward_type
}) {
achievement_id
id
reward_data
timestamp
type
}
}
`,
variables: {
achievement_id: newAchievement.id,
reward_type: 'sticker pack',
reward_data: {
...shopifyDiscountCode,
},
},
});
if (!newReward) {
return {
statusCode: 500,
body: 'Oh no! Check reward ran into an error!',
};
}
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers':
'Origin, X-Requested-With, Content-Type, Accept',
},
body: 'Success! Reward was created successfully!',
};
};