Skip to content

Commit b7ce7c1

Browse files
authored
Merge pull request #7 from cap-js/refactor_notification
Refactor Post Notification
2 parents 79991f1 + 06ec403 commit b7ce7c1

File tree

3 files changed

+118
-79
lines changed

3 files changed

+118
-79
lines changed

lib/notifications.js

Lines changed: 8 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,64 +1,22 @@
1-
const { executeHttpRequest, buildCsrfHeaders } = require("@sap-cloud-sdk/core");
2-
const { getNotificationDestination, getNotificationTypesKeyWithPrefix } = require("./utils");
1+
const { buildCsrfHeaders } = require("@sap-cloud-sdk/core");
2+
const { getNotificationDestination, executeRequest, buildNotification } = require("./utils");
33

44
const NOTIFICATIONS_DESTINATION_NAME = cds.env.requires.notifications?.destination ?? "SAP_Notifications";
55
const NOTIFICATIONS_API_ENDPOINT = "v2/Notification.svc";
66

7-
function createNotificationObject(recipients, notificationTypeKey, notificationTypeVersion, notificationData, language = "en") {
8-
let aProperties = [];
9-
if (typeof notificationData === "object") {
10-
for (sProperty of Object.keys(notificationData)) {
11-
//TODO: recheck if can be sent from application. Check for localization
12-
aProperties.push({
13-
Key: sProperty,
14-
Language: language,
15-
Value: notificationData[sProperty],
16-
Type: "String",
17-
IsSensitive: false,
18-
});
19-
}
20-
}
21-
22-
const notificationTypeKeyWithPrefix = getNotificationTypesKeyWithPrefix(notificationTypeKey);
23-
24-
return {
25-
NotificationTypeKey: notificationTypeKeyWithPrefix,
26-
NotificationTypeVersion: notificationTypeVersion,
27-
Priority: "High",
28-
Properties: aProperties,
29-
Recipients: recipients.map((recipient) => ({ RecipientId: recipient })),
30-
};
31-
}
32-
33-
async function postNotification(
34-
recipients,
35-
notificationTypeKey,
36-
notificationTypeVersion,
37-
notificationData,
38-
language = "en",
39-
destination = NOTIFICATIONS_DESTINATION_NAME
40-
) {
41-
const notification = createNotificationObject(recipients, notificationTypeKey, notificationTypeVersion, notificationData, language);
42-
const notifServiceDest = await getNotificationDestination(destination);
7+
async function postNotification() {
8+
const notifServiceDest = await getNotificationDestination(NOTIFICATIONS_DESTINATION_NAME);
439
const csrfHeaders = await buildCsrfHeaders(notifServiceDest, {
4410
url: NOTIFICATIONS_API_ENDPOINT,
4511
});
4612

47-
let response = {};
48-
try {
49-
response = await executeHttpRequest(notifServiceDest, {
50-
url: `${NOTIFICATIONS_API_ENDPOINT}/Notifications`,
51-
method: "post",
52-
data: notification,
53-
headers: csrfHeaders,
54-
});
55-
} catch (e) {
56-
console.log(e);
13+
const notification = buildNotification(arguments);
14+
15+
if (notification) {
16+
return (await executeRequest("post", `${NOTIFICATIONS_API_ENDPOINT}/Notifications`, notification, notifServiceDest, csrfHeaders)).data.d;
5717
}
58-
return response.data.d;
5918
}
6019

6120
module.exports = {
62-
createNotificationObject,
6321
postNotification
6422
};

lib/utils.js

Lines changed: 93 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
const fs = require('fs');
22
const { basename } = require('path')
33
const cds = require("@sap/cds");
4-
const { getDestination } = require("@sap-cloud-sdk/core");
4+
const { executeHttpRequest, getDestination } = require("@sap-cloud-sdk/core");
5+
const PRIORITIES = ["LOW", "NEUTRAL", "MEDIUM", "HIGH"];
56

67
const messages = {
78
INVALID_NOTIFICATION_TYPES: "Notification Types must contain the following keys: 'NotificationTypeKey' and 'NotificationTypeVersion'.",
89
DESTINATION_NOT_FOUND: "Failed to get destination: ",
10+
MANDATORY_PARAMETER_NOT_PASSED: "Recipients, priority and title are mandatory parameters",
911
};
1012

1113
function validateNotificationTypes(notificationTypes) {
@@ -16,6 +18,20 @@ function validateNotificationTypes(notificationTypes) {
1618
});
1719
}
1820

21+
function validateNotifyParameters(recipients, priority, title) {
22+
if (!recipients || !priority || !title) {
23+
console.log(messages.MANDATORY_PARAMETER_NOT_PASSED);
24+
return false;
25+
}
26+
27+
if (!PRIORITIES.includes(priority)) {
28+
console.log(`Invalid priority ${priority}. Allowed priorities are LOW, NEUTRAL, MEDIUM, HIGH`);
29+
return false;
30+
}
31+
32+
return true;
33+
}
34+
1935
function doesKeyExist(obj, key) {
2036
return typeof(key) === 'string' && typeof(obj) === 'object' && key in obj;
2137
}
@@ -41,12 +57,87 @@ function getNotificationTypesKeyWithPrefix(notificationTypeKey) {
4157
return `${prefix}/${notificationTypeKey}`;
4258
}
4359

60+
async function executeRequest(httpMethod, targetUrl, payload, notifServiceDest, csrfHeaders) {
61+
let response = {};
62+
try {
63+
response = await executeHttpRequest(notifServiceDest, {
64+
url: targetUrl,
65+
method: httpMethod,
66+
data: payload,
67+
headers: csrfHeaders,
68+
});
69+
} catch (e) {
70+
console.log(e);
71+
}
72+
return response;
73+
}
74+
75+
function buildDefaultNotification(
76+
recipients,
77+
priority,
78+
title,
79+
description
80+
) {
81+
const properties = [
82+
{
83+
Key: "title",
84+
Language: "en",
85+
Value: title,
86+
Type: "String",
87+
IsSensitive: false,
88+
},
89+
{
90+
Key: "description",
91+
Language: "en",
92+
Value: description,
93+
Type: "String",
94+
IsSensitive: false,
95+
},
96+
];
97+
98+
return {
99+
NotificationTypeKey: "Default",
100+
NotificationTypeVersion: "1",
101+
Priority: priority,
102+
Properties: properties,
103+
Recipients: recipients.map((recipient) => ({ RecipientId: recipient }))
104+
};
105+
}
106+
107+
function buildNotification(passedArguments) {
108+
let notification;
109+
if (passedArguments.length == 1 && typeof passedArguments[0] === "object" && !Array.isArray(passedArguments[0])) {
110+
notification = passedArguments[0];
111+
notification["NotificationTypeKey"] = getNotificationTypesKeyWithPrefix(notification["NotificationTypeKey"]);
112+
} else {
113+
const recipients = passedArguments[0];
114+
const priority = passedArguments[1];
115+
const title = passedArguments[2];
116+
const description = passedArguments[3] ? passedArguments[3] : "";
117+
118+
if (!validateNotifyParameters(recipients, priority, title)) {
119+
return;
120+
}
121+
122+
notification = buildDefaultNotification(
123+
recipients,
124+
priority,
125+
title,
126+
description
127+
);
128+
}
129+
130+
return notification;
131+
}
132+
44133
module.exports = {
45134
messages,
46135
validateNotificationTypes,
47136
readFile,
48137
doesKeyExist,
49138
getNotificationDestination,
50139
getPrefix,
51-
getNotificationTypesKeyWithPrefix
140+
getNotificationTypesKeyWithPrefix,
141+
executeRequest,
142+
buildNotification
52143
};

srv/notifyToConsole.js

Lines changed: 17 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,30 @@
11
const NotificationService = require('./service');
2-
const cds = require("@sap/cds");
3-
const notifier = require("../lib/notifications");
4-
const { doesKeyExist, getNotificationTypesKeyWithPrefix } = require('../lib/utils');
2+
const { buildNotification, readFile, doesKeyExist } = require("./../lib/utils");
3+
const { createNotificationTypesMap } = require("./../lib/notificationTypes");
54

65
module.exports = class NotifyToConsole extends NotificationService {
76
async init() {
87
// call NotificationService's init
98
await super.init();
109
}
1110

12-
notify (
13-
recipients,
14-
notificationTypeKey,
15-
notificationTypeVersion,
16-
notificationData,
17-
language = "en"
18-
) {
11+
notify() {
1912

20-
const key = getNotificationTypesKeyWithPrefix(notificationTypeKey);
21-
const types = cds.notifications.local.types;
22-
if (!doesKeyExist(types, key)) {
23-
throw new Error(`Invalid Notification Type Key: ${notificationTypeKey}`);
24-
}
25-
26-
if (!doesKeyExist(types[key], notificationTypeVersion)) {
27-
throw new Error(`Invalid Notification Type Version for Key ${notificationTypeKey}: ${notificationTypeVersion}`);
28-
}
13+
const notification = buildNotification(arguments);
2914

30-
const notification = notifier.createNotificationObject(
31-
recipients,
32-
notificationTypeKey,
33-
notificationTypeVersion,
34-
notificationData,
35-
language
36-
);
15+
if (notification) {
16+
console.log(`SAP Alert Notification service notification: ${JSON.stringify(notification, null, 2)}`);
3717

38-
console.log(`[ans] - ${notificationTypeKey} - ${notificationTypeVersion}:`, notification);
18+
const existingTypes = cds.notifications.local.types;
19+
20+
if (!doesKeyExist(existingTypes, notification["NotificationTypeKey"])) {
21+
console.log(`Notification Type ${notification["NotificationTypeKey"]} is not in the notification types file`);
22+
}
23+
24+
if (!doesKeyExist(existingTypes[notification["NotificationTypeKey"]], notification["NotificationTypeVersion"])) {
25+
console.log(`Notification Type Version ${notification["NotificationTypeVersion"]} for type ${notification["NotificationTypeKey"]} is not in the notification types file`);
26+
}
27+
}
28+
3929
}
4030
}

0 commit comments

Comments
 (0)