generated from ecomplus/application-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webhook.js
61 lines (53 loc) · 1.62 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
// read configured E-Com Plus app data
const getAppData = require('./../../lib/store-api/get-app-data')
const SKIP_TRIGGER_NAME = 'SkipTrigger'
const ECHO_SUCCESS = 'SUCCESS'
const ECHO_SKIP = 'SKIP'
const ECHO_API_ERROR = 'STORE_API_ERR'
exports.post = ({ appSdk }, req, res) => {
// receiving notification from Store API
const { storeId } = req
/**
* Treat E-Com Plus trigger body here
* Ref.: https://developers.e-com.plus/docs/api/#/store/triggers/
*/
const trigger = req.body
// get app configured options
getAppData({ appSdk, storeId })
.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 */
// all done
res.send(ECHO_SUCCESS)
})
.catch(err => {
if (err.name === SKIP_TRIGGER_NAME) {
// trigger ignored by app configuration
res.send(ECHO_SKIP)
} else if (err.appWithoutAuth === true) {
const msg = `Webhook for ${storeId} unhandled with no authentication found`
const error = new Error(msg)
error.trigger = JSON.stringify(trigger)
console.error(error)
res.status(412).send(msg)
} else {
// console.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
})
}
})
}