generated from ecomplus/application-starter
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwebhook.js
229 lines (214 loc) · 7.94 KB
/
webhook.js
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
/* eslint-disable no-loop-func, promise/no-nesting */
const { logger } = require('../../context')
const { baseUri, operatorToken } = require('./../../__env')
// read configured E-Com Plus app data
const getAppData = require('./../../lib/store-api/get-app-data')
// async integration handlers
const integrationHandlers = {
exportation: {
product_ids: require('./../../lib/integration/export-product'),
order_ids: require('./../../lib/integration/export-order')
},
importation: {
skus: require('./../../lib/integration/import-product'),
order_numbers: require('./../../lib/integration/import-order')
}
}
const SKIP_TRIGGER_NAME = 'SkipTrigger'
const ECHO_SUCCESS = 'SUCCESS'
const ECHO_SKIP = 'SKIP'
const ECHO_API_ERROR = 'STORE_API_ERR'
const handlingIds = []
const removeFromQueue = (resourceId) => {
logger.info(handlingIds)
const handlingIndex = handlingIds.indexOf(resourceId)
handlingIds.splice(handlingIndex, 1)
}
exports.post = async ({ appSdk, admin }, req, res) => {
// receiving notification from Store API
const { storeId } = req
if (req.get('host') && !baseUri.includes(req.get('host'))) {
logger.info('>>> Proxy to function v2')
const axios = require('axios')
try {
const { status, data } = await axios.post(req.url, req.body, {
baseURL: baseUri,
headers: {
'x-store-id': storeId,
'x-operator-token': operatorToken
}
})
logger.info(`>>> Webhook proxy response: ${status} ${data}`)
return res.status(status).send(data)
} catch (error) {
const err = new Error('Error proxying to function v2')
err.config = error.config
err.response = {
status: error.response.status,
data: error.response.data
}
logger.error(err)
}
}
/**
* Treat E-Com Plus trigger body here
* Ref.: https://developers.e-com.plus/docs/api/#/store/triggers/
*/
const trigger = req.body
const resourceId = trigger.resource_id || trigger.inserted_id
logger.info(`>> ${resourceId} - Action: ${trigger.action}`)
if (!handlingIds.includes(resourceId)) {
handlingIds.push(resourceId)
const key = `${trigger.resource}_${resourceId}`
// get app configured options
appSdk.getAuth(storeId)
.then(auth => {
return getAppData({ appSdk, storeId, auth })
.then(appData => {
if (
Array.isArray(appData.ignore_triggers) &&
appData.ignore_triggers.indexOf(trigger.resource) > -1
) {
// ignore current trigger
const err = new Error()
err.name = SKIP_TRIGGER_NAME
throw err
}
/* DO YOUR CUSTOM STUFF HERE */
logger.info(`> Webhook #${storeId} ${resourceId} [${trigger.resource}]`)
const tinyToken = appData.tiny_api_token
if (typeof tinyToken === 'string' && tinyToken) {
let integrationConfig
let canCreateNew = false
switch (trigger.resource) {
case 'applications':
integrationConfig = appData
canCreateNew = true
break
case 'products':
if (trigger.body) {
if (trigger.action === 'create') {
if (!appData.new_products) {
break
}
canCreateNew = true
} else if (!trigger.body.price || !appData.update_price) {
break
}
integrationConfig = {
_exportation: {
product_ids: [resourceId]
}
}
}
break
case 'orders':
if (trigger.body) {
canCreateNew = Boolean(appData.new_orders)
integrationConfig = {
_exportation: {
order_ids: [resourceId]
}
}
}
break
}
if (integrationConfig) {
const actions = Object.keys(integrationHandlers)
actions.forEach(action => {
for (let i = 1; i <= 3; i++) {
actions.push(`${('_'.repeat(i))}${action}`)
}
})
for (let i = 0; i < actions.length; i++) {
const action = actions[i]
const actionQueues = integrationConfig[action]
if (typeof actionQueues === 'object' && actionQueues) {
for (const queue in actionQueues) {
const ids = actionQueues[queue]
if (Array.isArray(ids) && ids.length) {
const isHiddenQueue = action.charAt(0) === '_'
const mustUpdateAppQueue = trigger.resource === 'applications'
const handlerName = action.replace(/^_+/, '')
const handler = integrationHandlers[handlerName][queue.toLowerCase()]
const nextId = ids[0]
if (
typeof nextId === 'string' &&
nextId.length &&
handler
) {
const debugFlag = `#${storeId} ${action}/${queue}/${nextId}`
const delayMs = 6000
logger.info(`> Starting ${debugFlag}`)
const queueEntry = { action, queue, nextId, key, mustUpdateAppQueue }
return new Promise((resolve, reject) => {
setTimeout(() => {
handler(
{ appSdk, storeId, auth },
tinyToken,
queueEntry,
appData,
canCreateNew,
isHiddenQueue
)
.then(() => resolve({ appData, action, queue }))
.catch(reject)
}, delayMs)
})
}
}
}
}
}
}
}
// nothing to do
return {}
})
.then(({ appData, action, queue }) => {
removeFromQueue(resourceId)
if (appData) {
if (appData[action] && Array.isArray(appData[action][queue])) {
res.status(202)
} else {
res.status(201)
}
res.send(`> Processed \`${action}.${queue}\``)
} else {
res.send(ECHO_SUCCESS)
}
return {}
})
})
.catch(err => {
removeFromQueue(resourceId)
if (err.name === SKIP_TRIGGER_NAME) {
// trigger ignored by app configuration
res.send(ECHO_SKIP)
} else {
if (err.response) {
const error = new Error('Webhook process request error')
error.config = JSON.stringify(err.config)
error.response = JSON.stringify({
status: err.response.status,
data: err.response.data
})
logger.error(error)
} else {
logger.error(err)
}
// request to Store API with error response
// return error status code
res.status(500)
const { message } = err
res.send({
error: ECHO_API_ERROR,
message
})
}
})
} else {
logger.info(`# Skipped in execution #${resourceId} [${trigger.resource} - ${trigger.action}]`)
res.status(203).send('Concurrent request with same ResourceId')
}
}