This repository was archived by the owner on Jan 6, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcds-plugin.js
More file actions
78 lines (68 loc) · 2.04 KB
/
Copy pathcds-plugin.js
File metadata and controls
78 lines (68 loc) · 2.04 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
const cds = require('@sap/cds');
const { getSettings } = require('./lib/settings');
const {
onCreate,
onRead,
beforeAll,
onUpdate,
onDelete,
} = require('./lib/handlers');
const sdmServices = [];
/**
* Initialize plugin and define its handlers.
*/
cds.once('served', services => {
if (cds.env.requires?.['sap-cap-sdm-plugin']) initializePlugin(services);
});
/**
* Initializes the plugin by setting up the CMIS client and registering service handlers.
*/
async function initializePlugin(services) {
getSettings();
cds.env.requires['cmis-client'] = { impl: `${__dirname}/srv/cmis/client` };
cds.env.requires['sdm-admin'] = { impl: `${__dirname}/srv/sdm/admin` };
// Get all services that has any entity annotated with @Sdm.Entity
sdmServices.push(...extractServicesWithAnnotations(services));
// Register our handlers for each one of those
for (let service of sdmServices) {
registerServiceHandlers(service);
}
}
/**
* Extracts services with the "@Sdm.Entity" annotation.
* @param {Object} services - All services.
* @returns {Array} An array of services with the "@Sdm.Entity" annotation.
*/
function extractServicesWithAnnotations(services) {
return Object.values(services)
.filter(service => service instanceof cds.ApplicationService)
.map(service => ({
name: service.name,
srv: service,
entities: Object.values(service.entities).filter(
entity => entity?.['@Sdm.Entity'],
),
}))
.filter(service => service.entities.length > 0);
}
const eventHandlersMap = {
READ: onRead,
CREATE: onCreate,
UPDATE: onUpdate,
DELETE: onDelete,
};
/**
* Register event handlers for the given service.
* @param {Object} service - The service to register handlers for.
*/
async function registerServiceHandlers(service) {
const { srv, entities } = service;
srv.prepend(() => {
for (let entity of entities) {
for (let [event, handler] of Object.entries(eventHandlersMap)) {
srv.on(event, entity.name, handler);
}
srv.before('*', entity.name, beforeAll);
}
});
}