-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcds-plugin.js
More file actions
66 lines (58 loc) · 2.55 KB
/
Copy pathcds-plugin.js
File metadata and controls
66 lines (58 loc) · 2.55 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
const cds = require('@sap/cds')
if (!cds.env.requires?.notifications?.enabled) return
const { buildNotificationFromEvent } = require('./lib/utils')
cds.build?.register?.('notifications', require("./lib/build"))
cds.on("loaded", m => {
for (const def of Object.values(m.definitions)) {
if (def.kind !== 'event') continue
if (!Object.keys(def).some(k => k === '@notification' || k.startsWith('@notification.'))) continue
if (!def.elements) def.elements = {}
if (!def.elements.recipients) {
def.elements.recipients = { items: { type: 'cds.String' } }
}
}
})
cds.on('serving', service => {
if (service.name === 'notifications' || service instanceof cds.DatabaseService) return
service.on('*', async (req, next) => {
let def = req.target ?? service.events?.[req.event]
if (!def || def.kind !== 'event') return next()
if (!Object.keys(def).some(k => k === '@notification' || k.startsWith('@notification.'))) return next()
if (!def.name) def = { ...def, name: req.event }
const notifications = await cds.connect.to('notifications')
const notification = await buildNotificationFromEvent(def, req.data)
try {
await notifications.notify(notification)
} catch (err) {
const LOG = cds.log('notifications')
LOG._error && LOG.error('Failed to send notification for event', def.name, err)
}
return next()
})
})
cds.once("served", async () => {
const { validateNotificationTypes, readFile } = require("./lib/utils")
const { createNotificationTypesMap } = require("./lib/notificationTypes")
const { notificationTypesFromModel } = require("./lib/compile")
const production = cds.env.profiles?.includes("production")
const typesPath = cds.env.requires?.notifications?.types
const kind = cds.env.requires?.notifications?.kind
const needsProcessing = kind === 'notify-to-rest' || !production
if (!needsProcessing) return
const model = cds.context?.model ?? cds.model
const notificationTypes = [
...notificationTypesFromModel(model),
...( typesPath ? readFile(typesPath) : [] )
]
if (validateNotificationTypes(notificationTypes)) {
if (kind === 'notify-to-rest') {
const { processNotificationTypes } = require('./lib/notificationTypes')
// deploy automatically on startup
await processNotificationTypes(notificationTypes)
} else if (!production) {
const notificationTypesMap = createNotificationTypesMap(notificationTypes, true)
cds.notifications = { local: { types: notificationTypesMap } }
}
}
require("@sap-cloud-sdk/util").setGlobalLogLevel("error")
})