@universis/webhooks 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/.gitlab-ci.yml +40 -0
  2. package/LICENSE +163 -0
  3. package/README.md +113 -0
  4. package/dist/SchemaLoader.d.ts +4 -0
  5. package/dist/SchemaLoader.js +46 -0
  6. package/dist/SchemaLoader.js.map +1 -0
  7. package/dist/WebHookService.d.ts +11 -0
  8. package/dist/WebHookService.js +272 -0
  9. package/dist/WebHookService.js.map +1 -0
  10. package/dist/config/models/WebHook.json +182 -0
  11. package/dist/config/models/WebHookAction.json +85 -0
  12. package/dist/config/models/WebHookConfiguration.json +66 -0
  13. package/dist/config/scope.access.js +30 -0
  14. package/dist/config/scope.access.js.map +1 -0
  15. package/dist/index.d.ts +2 -0
  16. package/dist/index.js +3 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/listeners/OnWebHook.js +33 -0
  19. package/dist/listeners/OnWebHook.js.map +1 -0
  20. package/dist/listeners/OnWebHookAction.js +53 -0
  21. package/dist/listeners/OnWebHookAction.js.map +1 -0
  22. package/dist/listeners/package.json +3 -0
  23. package/jest.config.js +202 -0
  24. package/jsconfig.json +8 -0
  25. package/package.json +65 -0
  26. package/src/SchemaLoader.d.ts +4 -0
  27. package/src/SchemaLoader.js +46 -0
  28. package/src/WebHookService.d.ts +11 -0
  29. package/src/WebHookService.js +275 -0
  30. package/src/config/models/WebHook.json +182 -0
  31. package/src/config/models/WebHookAction.json +85 -0
  32. package/src/config/models/WebHookConfiguration.json +66 -0
  33. package/src/config/scope.access.js +34 -0
  34. package/src/index.d.ts +2 -0
  35. package/src/index.js +2 -0
  36. package/src/listeners/OnWebHook.js +37 -0
  37. package/src/listeners/OnWebHookAction.js +56 -0
  38. package/src/listeners/package.json +3 -0
package/.gitlab-ci.yml ADDED
@@ -0,0 +1,40 @@
1
+ image: node:20
2
+
3
+ stages:
4
+ - test
5
+ - deploy
6
+
7
+ publish:
8
+ stage: deploy
9
+ needs: [lint, audit]
10
+ rules:
11
+ - if: $CI_PROJECT_NAMESPACE == "universis" && $CI_COMMIT_REF_PROTECTED == "true"
12
+ changes:
13
+ - package.json
14
+ script:
15
+ - npm i
16
+ - npm run build
17
+ - echo //registry.npmjs.org/:_authToken=$NPM_TOKEN > .npmrc
18
+ # Extract a few values from package.json
19
+ - NPM_PACKAGE_NAME=$(node -p "require('./package.json').name")
20
+ - NPM_PACKAGE_VERSION=$(node -p "require('./package.json').version")
21
+ # Compare the version in package.json to all published versions.
22
+ # If the package.json version has not yet been published, run `npm publish`.
23
+ - |
24
+ if [[ $(npm view "${NPM_PACKAGE_NAME}" versions) != *"'${NPM_PACKAGE_VERSION}'"* ]]; then
25
+ npm publish --access public
26
+ else
27
+ echo "Version ${NPM_PACKAGE_VERSION} of ${NPM_PACKAGE_NAME} has already been published, so no new version has been published."
28
+ fi
29
+
30
+ lint:
31
+ stage: test
32
+ script:
33
+ - npm i
34
+ - npx eslint src --quiet
35
+
36
+ audit:
37
+ stage: test
38
+ script:
39
+ - npm i
40
+ - npm audit --production
package/LICENSE ADDED
@@ -0,0 +1,163 @@
1
+ GNU Lesser General Public License
2
+ =================================
3
+
4
+ _Version 3, 29 June 2007_
5
+ _Copyright © 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;_
6
+
7
+ Everyone is permitted to copy and distribute verbatim copies
8
+ of this license document, but changing it is not allowed.
9
+
10
+
11
+ This version of the GNU Lesser General Public License incorporates
12
+ the terms and conditions of version 3 of the GNU General Public
13
+ License, supplemented by the additional permissions listed below.
14
+
15
+ ### 0. Additional Definitions
16
+
17
+ As used herein, “this License” refers to version 3 of the GNU Lesser
18
+ General Public License, and the “GNU GPL” refers to version 3 of the GNU
19
+ General Public License.
20
+
21
+ “The Library” refers to a covered work governed by this License,
22
+ other than an Application or a Combined Work as defined below.
23
+
24
+ An “Application” is any work that makes use of an interface provided
25
+ by the Library, but which is not otherwise based on the Library.
26
+ Defining a subclass of a class defined by the Library is deemed a mode
27
+ of using an interface provided by the Library.
28
+
29
+ A “Combined Work” is a work produced by combining or linking an
30
+ Application with the Library. The particular version of the Library
31
+ with which the Combined Work was made is also called the “Linked
32
+ Version”.
33
+
34
+ The “Minimal Corresponding Source” for a Combined Work means the
35
+ Corresponding Source for the Combined Work, excluding any source code
36
+ for portions of the Combined Work that, considered in isolation, are
37
+ based on the Application, and not on the Linked Version.
38
+
39
+ The “Corresponding Application Code” for a Combined Work means the
40
+ object code and/or source code for the Application, including any data
41
+ and utility programs needed for reproducing the Combined Work from the
42
+ Application, but excluding the System Libraries of the Combined Work.
43
+
44
+ ### 1. Exception to Section 3 of the GNU GPL
45
+
46
+ You may convey a covered work under sections 3 and 4 of this License
47
+ without being bound by section 3 of the GNU GPL.
48
+
49
+ ### 2. Conveying Modified Versions
50
+
51
+ If you modify a copy of the Library, and, in your modifications, a
52
+ facility refers to a function or data to be supplied by an Application
53
+ that uses the facility (other than as an argument passed when the
54
+ facility is invoked), then you may convey a copy of the modified
55
+ version:
56
+
57
+ * **a)** under this License, provided that you make a good faith effort to
58
+ ensure that, in the event an Application does not supply the
59
+ function or data, the facility still operates, and performs
60
+ whatever part of its purpose remains meaningful, or
61
+
62
+ * **b)** under the GNU GPL, with none of the additional permissions of
63
+ this License applicable to that copy.
64
+
65
+ ### 3. Object Code Incorporating Material from Library Header Files
66
+
67
+ The object code form of an Application may incorporate material from
68
+ a header file that is part of the Library. You may convey such object
69
+ code under terms of your choice, provided that, if the incorporated
70
+ material is not limited to numerical parameters, data structure
71
+ layouts and accessors, or small macros, inline functions and templates
72
+ (ten or fewer lines in length), you do both of the following:
73
+
74
+ * **a)** Give prominent notice with each copy of the object code that the
75
+ Library is used in it and that the Library and its use are
76
+ covered by this License.
77
+ * **b)** Accompany the object code with a copy of the GNU GPL and this license
78
+ document.
79
+
80
+ ### 4. Combined Works
81
+
82
+ You may convey a Combined Work under terms of your choice that,
83
+ taken together, effectively do not restrict modification of the
84
+ portions of the Library contained in the Combined Work and reverse
85
+ engineering for debugging such modifications, if you also do each of
86
+ the following:
87
+
88
+ * **a)** Give prominent notice with each copy of the Combined Work that
89
+ the Library is used in it and that the Library and its use are
90
+ covered by this License.
91
+
92
+ * **b)** Accompany the Combined Work with a copy of the GNU GPL and this license
93
+ document.
94
+
95
+ * **c)** For a Combined Work that displays copyright notices during
96
+ execution, include the copyright notice for the Library among
97
+ these notices, as well as a reference directing the user to the
98
+ copies of the GNU GPL and this license document.
99
+
100
+ * **d)** Do one of the following:
101
+ - **0)** Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+ - **1)** Use a suitable shared library mechanism for linking with the
109
+ Library. A suitable mechanism is one that **(a)** uses at run time
110
+ a copy of the Library already present on the user's computer
111
+ system, and **(b)** will operate properly with a modified version
112
+ of the Library that is interface-compatible with the Linked
113
+ Version.
114
+
115
+ * **e)** Provide Installation Information, but only if you would otherwise
116
+ be required to provide such information under section 6 of the
117
+ GNU GPL, and only to the extent that such information is
118
+ necessary to install and execute a modified version of the
119
+ Combined Work produced by recombining or relinking the
120
+ Application with a modified version of the Linked Version. (If
121
+ you use option **4d0**, the Installation Information must accompany
122
+ the Minimal Corresponding Source and Corresponding Application
123
+ Code. If you use option **4d1**, you must provide the Installation
124
+ Information in the manner specified by section 6 of the GNU GPL
125
+ for conveying Corresponding Source.)
126
+
127
+ ### 5. Combined Libraries
128
+
129
+ You may place library facilities that are a work based on the
130
+ Library side by side in a single library together with other library
131
+ facilities that are not Applications and are not covered by this
132
+ License, and convey such a combined library under terms of your
133
+ choice, if you do both of the following:
134
+
135
+ * **a)** Accompany the combined library with a copy of the same work based
136
+ on the Library, uncombined with any other library facilities,
137
+ conveyed under the terms of this License.
138
+ * **b)** Give prominent notice with the combined library that part of it
139
+ is a work based on the Library, and explaining where to find the
140
+ accompanying uncombined form of the same work.
141
+
142
+ ### 6. Revised Versions of the GNU Lesser General Public License
143
+
144
+ The Free Software Foundation may publish revised and/or new versions
145
+ of the GNU Lesser General Public License from time to time. Such new
146
+ versions will be similar in spirit to the present version, but may
147
+ differ in detail to address new problems or concerns.
148
+
149
+ Each version is given a distinguishing version number. If the
150
+ Library as you received it specifies that a certain numbered version
151
+ of the GNU Lesser General Public License “or any later version”
152
+ applies to it, you have the option of following the terms and
153
+ conditions either of that published version or of any later version
154
+ published by the Free Software Foundation. If the Library as you
155
+ received it does not specify a version number of the GNU Lesser
156
+ General Public License, you may choose any version of the GNU Lesser
157
+ General Public License ever published by the Free Software Foundation.
158
+
159
+ If the Library as you received it specifies that a proxy can decide
160
+ whether future versions of the GNU Lesser General Public License shall
161
+ apply, that proxy's public statement of acceptance of any version is
162
+ permanent authorization for you to choose that version for the
163
+ Library.
package/README.md ADDED
@@ -0,0 +1,113 @@
1
+ # @universis/hooks
2
+
3
+ Universis API Server module providing webhook functionality.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @universis/webhooks
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ Install service in your Universis API Server configuration:
14
+
15
+ ```json
16
+ {
17
+ "services": [
18
+ {
19
+ "serviceType": "@universis/webhooks#WebHookService"
20
+ }
21
+ ]
22
+ }
23
+ ```
24
+
25
+ ## Configuration
26
+
27
+ The service can be configured with the following options:
28
+ ```json
29
+ {
30
+ "settings": {
31
+ "universis": {
32
+ "webhooks": {
33
+ "logLevel": "info",
34
+ "logDir": "./log"
35
+ }
36
+ }
37
+ }
38
+ }
39
+ ```
40
+
41
+ where `logLevel` can be one of `error`, `warn`, `info`, `verbose`, or `debug` and `logDir` is the directory where logs will be stored.
42
+
43
+ ## Features
44
+
45
+ - Create, read, update, and delete webhooks.
46
+ - Trigger webhooks on specific events.
47
+
48
+ ## API Endpoints
49
+
50
+ - `GET /api/webHookActions`: Retrieve a list of available webhook actions. The operation requires `webhooks:read` permission.
51
+ - `POST /api/webhooks`: Create a new webhook. The operation requires `webhooks:write` permission.
52
+ - `GET /api/webhooks`: Retrieve a list of webhooks. The operation requires `webhooks:read` permission.
53
+ - `GET /api/webhooks/:id`: Retrieve a specific webhook by ID. The operation requires `webhooks:read` permission.
54
+ - `PUT /api/webhooks/:id`: Update a specific webhook by ID. The operation requires `webhooks:write` permission.
55
+ - `DELETE /api/webhooks/:id`: Delete a specific webhook by ID. The operation requires `webhooks
56
+
57
+ ## Create a new webhook
58
+
59
+ To create a new webhook, send a POST request to `/api/webhooks` with the following JSON body:
60
+
61
+ ```json
62
+ {
63
+ "action": "update_user",
64
+ "active": true,
65
+ "config": {
66
+ "url": "https://example.com/webhook",
67
+ "contentType": "application/json"
68
+ }
69
+ ```
70
+
71
+ ## Delete a webhook
72
+
73
+ To delete a webhook, send a DELETE request to `/api/webhooks/:id`, where `:id` is the unique identifier of the webhook you want to delete.
74
+ The operation requires `webhooks:write` permission.
75
+
76
+ ## Update a webhook
77
+
78
+ To update a webhook, send a POST request to `/api/webhooks/` containing the updated fields in the JSON body.
79
+
80
+ ```json
81
+ {
82
+ "id": "7085b05b-8da6-4004-b5cc-7b204725d63f",
83
+ "action": "update_action",
84
+ "active": false,
85
+ "config": {
86
+ "url": "https://newexample.com/webhook",
87
+ "contentType": "application/xml"
88
+ }
89
+ }
90
+ ```
91
+
92
+ The operation requires `webhooks:write` permission. The `active` field can be used to enable or disable the webhook wihout deleting it.
93
+ An inactive webhook will not be triggered during events.
94
+
95
+ ## Triggering Webhooks
96
+
97
+ Webhooks are triggered automatically when the specified action occurs in the system. The payload sent will contain relevant data about the event.
98
+
99
+ ```json
100
+ {
101
+ "event": "update_user",
102
+ "entityType": "User",
103
+ "entitySet": "Users",
104
+ "origin": "https://api.example.com",
105
+ "target": {
106
+ "id": "12345"
107
+ }
108
+ }
109
+ ```
110
+
111
+ where `event` is the action that triggered the webhook, `entityType` is the type of entity involved, `entitySet` is the collection the entity belongs to, and `target` contains details about the specific entity.
112
+
113
+ The payload does not include other metadata except for the target identifier. The webhook receiver can use this identifier to fetch additional details if needed.
@@ -0,0 +1,4 @@
1
+ import { FileSchemaLoaderStrategy } from '@themost/data';
2
+ export declare class SchemaLoader extends FileSchemaLoaderStrategy {
3
+
4
+ }
@@ -0,0 +1,46 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.SchemaLoader = void 0;var _data = require("@themost/data");
2
+ var _path = _interopRequireDefault(require("path"));function _interopRequireDefault(e) {return e && e.__esModule ? e : { default: e };}
3
+
4
+
5
+ if (typeof _data.ValueDialect.prototype.$literal === 'undefined') {
6
+ /**
7
+ * Add $literal support to ValueDialect
8
+ */
9
+ _data.ValueDialect.prototype.$literal = async function (value) {
10
+ return value;
11
+ };
12
+ }
13
+
14
+ /**
15
+ * A schema loader for loading extra data models
16
+ */
17
+ class SchemaLoader extends _data.FileSchemaLoaderStrategy {
18
+
19
+ /**
20
+ * @param {import('@themost/data').ConfigurationBase} config
21
+ */
22
+ constructor(config) {
23
+ super(config);
24
+ // set model path
25
+ this.setModelPath(_path.default.resolve(__dirname, 'config/models'));
26
+ }
27
+
28
+ getModelDefinition(name) {
29
+ const model = super.getModelDefinition.bind(this)(name);
30
+ if (model) {
31
+ if (Array.isArray(model.eventListeners)) {
32
+ model.eventListeners.forEach((eventListener) => {
33
+ if (eventListener.type.indexOf('.') === 0) {
34
+ eventListener.type = _path.default.resolve(__dirname, eventListener.type);
35
+ }
36
+ });
37
+ }
38
+ if (model.classPath && model.classPath.indexOf('.') === 0) {
39
+ model.classPath = _path.default.resolve(__dirname, model.classPath);
40
+ }
41
+ }
42
+ return model;
43
+ }
44
+
45
+ }exports.SchemaLoader = SchemaLoader;
46
+ //# sourceMappingURL=SchemaLoader.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SchemaLoader.js","names":["_data","require","_path","_interopRequireDefault","e","__esModule","default","ValueDialect","prototype","$literal","value","SchemaLoader","FileSchemaLoaderStrategy","constructor","config","setModelPath","path","resolve","__dirname","getModelDefinition","name","model","bind","Array","isArray","eventListeners","forEach","eventListener","type","indexOf","classPath","exports"],"sources":["../src/SchemaLoader.js"],"sourcesContent":["import {FileSchemaLoaderStrategy} from '@themost/data';\nimport path from 'path';\nimport { ValueDialect } from '@themost/data';\n\nif (typeof ValueDialect.prototype.$literal === 'undefined') {\n /**\n * Add $literal support to ValueDialect\n */\n ValueDialect.prototype.$literal = async function (value) {\n return value;\n }\n}\n\n/**\n * A schema loader for loading extra data models\n */\nexport class SchemaLoader extends FileSchemaLoaderStrategy {\n\n /**\n * @param {import('@themost/data').ConfigurationBase} config\n */\n constructor(config) {\n super(config);\n // set model path\n this.setModelPath(path.resolve(__dirname, 'config/models'));\n }\n\n getModelDefinition(name) {\n const model = super.getModelDefinition.bind(this)(name);\n if (model) {\n if (Array.isArray(model.eventListeners) ) {\n model.eventListeners.forEach(eventListener => {\n if (eventListener.type.indexOf('.') === 0) {\n eventListener.type = path.resolve(__dirname, eventListener.type);\n }\n });\n }\n if (model.classPath && model.classPath.indexOf('.')===0) {\n model.classPath= path.resolve(__dirname, model.classPath);\n }\n }\n return model;\n }\n\n}\n\n"],"mappings":"yGAAA,IAAAA,KAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAC,sBAAA,CAAAF,OAAA,UAAwB,SAAAE,uBAAAC,CAAA,UAAAA,CAAA,IAAAA,CAAA,CAAAC,UAAA,GAAAD,CAAA,KAAAE,OAAA,EAAAF,CAAA;;;AAGxB,IAAI,OAAOG,kBAAY,CAACC,SAAS,CAACC,QAAQ,KAAK,WAAW,EAAE;EACxD;AACJ;AACA;EACIF,kBAAY,CAACC,SAAS,CAACC,QAAQ,GAAG,gBAAgBC,KAAK,EAAE;IACrD,OAAOA,KAAK;EAChB,CAAC;AACL;;AAEA;AACA;AACA;AACO,MAAMC,YAAY,SAASC,8BAAwB,CAAC;;EAEvD;AACJ;AACA;EACIC,WAAWA,CAACC,MAAM,EAAE;IAChB,KAAK,CAACA,MAAM,CAAC;IACb;IACA,IAAI,CAACC,YAAY,CAACC,aAAI,CAACC,OAAO,CAACC,SAAS,EAAE,eAAe,CAAC,CAAC;EAC/D;;EAEAC,kBAAkBA,CAACC,IAAI,EAAE;IACrB,MAAMC,KAAK,GAAG,KAAK,CAACF,kBAAkB,CAACG,IAAI,CAAC,IAAI,CAAC,CAACF,IAAI,CAAC;IACvD,IAAIC,KAAK,EAAE;MACP,IAAIE,KAAK,CAACC,OAAO,CAACH,KAAK,CAACI,cAAc,CAAC,EAAG;QACtCJ,KAAK,CAACI,cAAc,CAACC,OAAO,CAAC,CAAAC,aAAa,KAAI;UAC1C,IAAIA,aAAa,CAACC,IAAI,CAACC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE;YACvCF,aAAa,CAACC,IAAI,GAAGZ,aAAI,CAACC,OAAO,CAACC,SAAS,EAAGS,aAAa,CAACC,IAAI,CAAC;UACrE;QACJ,CAAC,CAAC;MACN;MACA,IAAIP,KAAK,CAACS,SAAS,IAAIT,KAAK,CAACS,SAAS,CAACD,OAAO,CAAC,GAAG,CAAC,KAAG,CAAC,EAAE;QACrDR,KAAK,CAACS,SAAS,GAAEd,aAAI,CAACC,OAAO,CAACC,SAAS,EAAEG,KAAK,CAACS,SAAS,CAAC;MAC7D;IACJ;IACA,OAAOT,KAAK;EAChB;;AAEJ,CAACU,OAAA,CAAApB,YAAA,GAAAA,YAAA","ignoreList":[]}
@@ -0,0 +1,11 @@
1
+ import { ApplicationService } from '@themost/common';
2
+ import {DataEventArgs} from '@themost/data';
3
+ import {JsonLogger} from '@themost/json-logger';
4
+
5
+ export declare class WebHookService extends ApplicationService {
6
+ readonly logger: JsonLogger;
7
+ refresh(): Promise<void>;
8
+ emit(event: DataEventArgs, extraArgs?: {
9
+ action?: string
10
+ }): void;
11
+ }
@@ -0,0 +1,272 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.WebHookService = void 0;
2
+
3
+ var _common = require("@themost/common");
4
+ var _scope = require("./config/scope.access");
5
+ var _data = require("@themost/data");
6
+
7
+
8
+
9
+
10
+
11
+ var _SchemaLoader = require("./SchemaLoader");
12
+ var _superagent = _interopRequireDefault(require("superagent"));
13
+ var _query = require("@themost/query");
14
+ var _jsonLogger = require("@themost/json-logger");
15
+ var _path = _interopRequireDefault(require("path"));
16
+ var _rotatingFileStream = require("rotating-file-stream");
17
+ var _dataModelFilter = require("@themost/data/data-model-filter.parser");
18
+ var _OnWebHookAction = require("./listeners/OnWebHookAction");function _interopRequireDefault(e) {return e && e.__esModule ? e : { default: e };} // noinspection NpmUsedModulesInstalled
19
+
20
+ class WebHookService extends _common.ApplicationService {
21
+ constructor(app) {
22
+ super(app);
23
+ /**
24
+ * @type {import('@themost/data').DefaultSchemaLoaderStrategy}
25
+ */
26
+ const schemaLoader = app.getConfiguration().getStrategy(_data.SchemaLoaderStrategy);
27
+ schemaLoader.loaders.push(new _SchemaLoader.SchemaLoader(app.getConfiguration()));
28
+ /**
29
+ * @type {import('@themost/data').ODataModelBuilder}
30
+ */
31
+ const builder = app.getService(_data.ODataModelBuilder);
32
+ if (builder) {
33
+ builder.clean(true);
34
+ }
35
+ // extend universis api scope access configuration
36
+ if (app && app.container) {
37
+ app.container.subscribe((container) => {
38
+ if (container) {
39
+ // add extra scope access elements
40
+ const scopeAccess = app.getConfiguration().getStrategy(function ScopeAccessConfiguration() {
41
+ });
42
+ if (scopeAccess != null) {
43
+ scopeAccess.elements.unshift(..._scope.WebHookScopeAccessElements);
44
+ }
45
+ }
46
+ });
47
+ }
48
+
49
+ // configure logger
50
+ // get options from configuration
51
+ const options = Object.assign({
52
+ logLevel: 'info',
53
+ logFormat: 'raw',
54
+ logDir: _path.default.join(process.cwd(), 'log')
55
+ }, app.getConfiguration().getSourceAt('settings/universis/webhooks'));
56
+ const logDir = options.logDir ? _path.default.resolve(options.logDir) : _path.default.join(process.cwd(), 'log');
57
+ const logFile = 'webhooks.log';
58
+ // create a rotating write stream
59
+ // noinspection JSValidateTypes
60
+ const logStream = (0, _rotatingFileStream.createStream)(logFile, {
61
+ interval: '1d', // rotate daily
62
+ path: logDir
63
+ });
64
+ this.logger = new _jsonLogger.JsonLogger({
65
+ level: options.logLevel,
66
+ format: options.logFormat,
67
+ stdout: logStream,
68
+ stderr: logStream
69
+ });
70
+ this.logger.info(`Universis WebHookService initialized with log level "${options.logLevel}"`);
71
+
72
+ if (app) {
73
+ const self = this;
74
+ setTimeout(() => {
75
+ (async () => {
76
+ await self.refresh();
77
+ })();
78
+ }, 1000);
79
+ }
80
+
81
+ }
82
+
83
+ /**
84
+ * Refresh web hook actions
85
+ * @returns {Promise<void>}
86
+ */
87
+ async refresh() {
88
+ /**
89
+ * @type {import('@themost/data').DataContext}
90
+ */
91
+ let context;
92
+ try {
93
+ // noinspection JSUnresolvedReference
94
+ context = this.getApplication().createContext();
95
+ this.logger.info('Registering existing web hook actions');
96
+ const items = await context.model('WebHookAction').asQueryable().take(-1).silent().getAllItems();
97
+ if (items.length > 0) {
98
+ this.logger.info(`Found ${items.length} web hook action(s). The operation will automatically register event listeners to the underlying data models.`);
99
+ }
100
+ for (const item of items) {
101
+ const model = context.model(item.about);
102
+ if (model) {
103
+ await new Promise((resolve, reject) => {
104
+ (0, _OnWebHookAction.afterSave)({ state: _data.DataObjectState.Insert, target: item, model }, (err) => {
105
+ if (err) {
106
+ return reject(err);
107
+ }
108
+ return resolve();
109
+ });
110
+ });
111
+ } else {
112
+ this.logger.warn(`Cannot register web hook action with name "${item.name || 'unknown'}" because model "${item.about}" does not exist.`);
113
+ }
114
+ }
115
+ } catch (err) {
116
+ this.logger.error('An error occurred when registering existing web hooks');
117
+ this.logger.error(err);
118
+ } finally {
119
+ if (context) {
120
+ await context.finalizeAsync();
121
+ }
122
+ }
123
+ }
124
+
125
+ /**
126
+ *
127
+ * @param {import('@themost/data').DataModel} model
128
+ * @param {*} target
129
+ * @param {string} filter
130
+ * @param {number} state
131
+ * @returns {Promise<boolean>}
132
+ */
133
+ async filterObjectAsync(model, target, filter, state) {
134
+ const parser = new _dataModelFilter.DataModelFilterParser(model);
135
+ const { $expand, $where } = await parser.parseAsync(filter);
136
+ const q = new _data.DataQueryable(model);
137
+ Object.assign(q.query, {
138
+ $where,
139
+ $expand
140
+ });
141
+ const { primaryKey } = model;
142
+ const id = target[primaryKey];
143
+ q.prepare();
144
+ if (state !== _data.DataObjectState.Delete) {
145
+ q.where(primaryKey).equal(id);
146
+ }
147
+ const exists = await q.count();
148
+ return exists > 0;
149
+ }
150
+
151
+ /**
152
+ * Emit web hook events
153
+ * @param {import('@themost/data').DataEventArgs} event
154
+ * @param {{action?: string, emit?: boolean}} extraArgs
155
+ */
156
+ emit(event, extraArgs) {
157
+ const context = event.model.context;
158
+ // get previous and current state of the entity
159
+ const { previous, target, state, model } = event;
160
+ /**
161
+ * @type {import('@themost/express').ExpressDataApplication|import('@themost/common').ApplicationBase}
162
+ */
163
+ const application = context.application;
164
+ // noinspection JSUnresolvedReference
165
+ /**
166
+ * @type {import('@themost/express').ExpressDataContext|import('@themost/data').DataContext}
167
+ */
168
+ const newContext = application.createContext();
169
+ const about = model.name;
170
+ const self = this;
171
+ (async function () {
172
+ // noinspection JSUnresolvedReference
173
+ const q = newContext.model('WebHook').asQueryable().where((x, about, state) => {
174
+ // noinspection JSBitwiseOperatorUsage
175
+ return x.action.about === about && x.action.state === state && x.active === true;
176
+ }, about, state).select((x) => {
177
+ return {
178
+ id: x.id,
179
+ config: x.config,
180
+ action: x.action,
181
+ about: x.action.about,
182
+ emit: x.emit,
183
+ username: x.owner.name,
184
+ filter: x.action.filter,
185
+ when: x.action.when
186
+ };
187
+ }).silent().take(25).skip(0);
188
+ // apply extra arguments for finding web hooks
189
+ const findArgs = Object.assign({ emit: true }, extraArgs || {});
190
+ q.prepare();
191
+ Object.keys(findArgs).forEach((key) => {
192
+ const value = findArgs[key];
193
+ q.query.$where ? q.and(key).equal(value) : q.where(key).equal(value);
194
+ });
195
+
196
+ const { viewAdapter: WebHooks } = newContext.model('WebHook');
197
+ const targetModel = newContext.model(about);
198
+ // get entity set
199
+ const builder = application.getService(_data.ODataModelBuilder);
200
+ const entitySet = builder.getEntityTypeEntitySet(targetModel.name);
201
+ const { primaryKey: key } = targetModel;
202
+ // get origin
203
+ const origin = context.getConfiguration().getSourceAt('settings/universis/api/origin');
204
+ /**
205
+ * @type {{total: number, skip: number, value: Array<{ id: string,config: { url: string, insecure: boolean, secret?: string, contentType: string }, emit: boolean, username: string,action: string,about: string,filter: string,when: string}>}} list
206
+ */
207
+ let list = await q.getList();
208
+ if (list.total > 0) {
209
+ while (list.total >= list.skip + list.value.length) {
210
+ for (const item of list.value) {
211
+ // set context user
212
+ newContext.user = {
213
+ name: item.username || 'anonymous'
214
+ };
215
+ try {
216
+ let send = true;
217
+ if (state === _data.DataObjectState.Insert) {
218
+ // validate the current state of a new object
219
+ const filter = item.when || item.filter;
220
+ send = await self.filterObjectAsync(targetModel, target, filter, state);
221
+ } else {
222
+ // validate previous state
223
+ send = await self.filterObjectAsync(targetModel, previous, item.when, state);
224
+ // validate current state
225
+ if (send && item.filter) {
226
+ if (state === _data.DataObjectState.Delete) {
227
+ send = await self.filterObjectAsync(targetModel, previous, item.filter, state);
228
+ } else {
229
+ send = await self.filterObjectAsync(targetModel, target, item.filter, state);
230
+ }
231
+ }
232
+ }
233
+ if (send) {
234
+ self.logger.info(`Sending web hook for model "${about}" to url "${item.config.url}"`);
235
+ // send web hook request
236
+ const result = await (0, _superagent.default)('post', item.config.url).
237
+ set('Content-Type', item.config.contentType).
238
+ send({
239
+ event: item.action,
240
+ entityType: targetModel.name,
241
+ entitySet: entitySet && entitySet.name,
242
+ origin: origin,
243
+ target: {
244
+ id: state === _data.DataObjectState.Insert ? target[key] : previous[key]
245
+ }
246
+ });
247
+ const lastResponse = {
248
+ status: result.status
249
+ };
250
+ self.logger.info(`Web hook for model "${about}" to url ${item.config.url} returned status ${result.status}`);
251
+ // update last response with an ad-hoc query
252
+ await newContext.db.executeAsync(
253
+ new _query.QueryExpression().update(WebHooks).set({
254
+ lastResponse: JSON.stringify(lastResponse)
255
+ }).where('id').equal(item.id),
256
+ []);
257
+ } else {
258
+ self.logger.debug(`Web hook for model "${about}" and object with identifier ${target[key]} to url "${item.config.url}" was filtered and not sent`);
259
+ }
260
+ } catch (err) {
261
+ self.logger.error(`Error sending web hook for model "${about}" to url "${item.config.url}"`);
262
+ self.logger.error(err);
263
+ }
264
+ }
265
+ list = await q.take(25).skip(list.skip + list.value.length);
266
+ }
267
+ }
268
+ })();
269
+ }
270
+
271
+ }exports.WebHookService = WebHookService;
272
+ //# sourceMappingURL=WebHookService.js.map