@universis/webhooks 1.2.0 → 1.2.4

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.
package/README.md CHANGED
@@ -22,6 +22,18 @@ Install service in your Universis API Server configuration:
22
22
  }
23
23
  ```
24
24
 
25
+ Include `@universis/webhooks` schema loader under `settings/schema`:
26
+
27
+ ```json
28
+ {
29
+ "schema": [
30
+ {
31
+ "loaderType": "@universis/webhooks#SchemaLoader"
32
+ }
33
+ ]
34
+ }
35
+ ```
36
+
25
37
  ## Configuration
26
38
 
27
39
  The service can be configured with the following options:
@@ -65,6 +77,7 @@ To create a new webhook, send a POST request to `/api/webhooks` with the followi
65
77
  "config": {
66
78
  "url": "https://example.com/webhook",
67
79
  "contentType": "application/json"
80
+ }
68
81
  }
69
82
  ```
70
83
 
@@ -7,8 +7,6 @@ var _data = require("@themost/data");
7
7
 
8
8
 
9
9
 
10
-
11
- var _SchemaLoader = require("./SchemaLoader");
12
10
  var _superagent = _interopRequireDefault(require("superagent"));
13
11
  var _query = require("@themost/query");
14
12
  var _jsonLogger = require("@themost/json-logger");
@@ -20,19 +18,6 @@ var _OnWebHookAction = require("./listeners/OnWebHookAction");function _interopR
20
18
  class WebHookService extends _common.ApplicationService {
21
19
  constructor(app) {
22
20
  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
21
  if (app && app.container) {
37
22
  app.container.subscribe((container) => {
38
23
  if (container) {
@@ -45,7 +30,6 @@ class WebHookService extends _common.ApplicationService {
45
30
  }
46
31
  });
47
32
  }
48
-
49
33
  // configure logger
50
34
  // get options from configuration
51
35
  const options = Object.assign({
@@ -1 +1 @@
1
- {"version":3,"file":"WebHookService.js","names":["_common","require","_scope","_data","_SchemaLoader","_superagent","_interopRequireDefault","_query","_jsonLogger","_path","_rotatingFileStream","_dataModelFilter","_OnWebHookAction","e","__esModule","default","WebHookService","ApplicationService","constructor","app","schemaLoader","getConfiguration","getStrategy","SchemaLoaderStrategy","loaders","push","SchemaLoader","builder","getService","ODataModelBuilder","clean","container","subscribe","scopeAccess","ScopeAccessConfiguration","elements","unshift","WebHookScopeAccessElements","options","Object","assign","logLevel","logFormat","logDir","path","join","process","cwd","getSourceAt","resolve","logFile","logStream","createStream","interval","logger","JsonLogger","level","format","stdout","stderr","info","self","setTimeout","refresh","context","getApplication","createContext","items","model","asQueryable","take","silent","getAllItems","length","item","about","Promise","reject","afterSave","state","DataObjectState","Insert","target","err","warn","name","error","finalizeAsync","filterObjectAsync","filter","parser","DataModelFilterParser","$expand","$where","parseAsync","q","DataQueryable","query","primaryKey","id","prepare","Delete","where","equal","exists","count","emit","event","extraArgs","previous","application","newContext","x","action","active","select","config","username","owner","when","skip","findArgs","keys","forEach","key","value","and","viewAdapter","WebHooks","targetModel","entitySet","getEntityTypeEntitySet","origin","list","getList","total","user","send","url","result","request","set","contentType","entityType","lastResponse","status","db","executeAsync","QueryExpression","update","JSON","stringify","debug","exports"],"sources":["../src/WebHookService.js"],"sourcesContent":["// noinspection NpmUsedModulesInstalled\n\nimport {ApplicationService} from '@themost/common';\nimport {WebHookScopeAccessElements} from './config/scope.access';\nimport {\n DataObjectState,\n DataQueryable,\n ODataModelBuilder,\n SchemaLoaderStrategy\n} from '@themost/data';\nimport {SchemaLoader} from './SchemaLoader';\nimport request from 'superagent';\nimport {QueryExpression} from '@themost/query';\nimport { JsonLogger } from '@themost/json-logger';\nimport path from 'path';\nimport { createStream } from 'rotating-file-stream';\nimport {DataModelFilterParser} from '@themost/data/data-model-filter.parser';\nimport { afterSave } from './listeners/OnWebHookAction';\n\nclass WebHookService extends ApplicationService {\n constructor(app) {\n super(app);\n /**\n * @type {import('@themost/data').DefaultSchemaLoaderStrategy}\n */\n const schemaLoader = app.getConfiguration().getStrategy(SchemaLoaderStrategy);\n schemaLoader.loaders.push(new SchemaLoader(app.getConfiguration()));\n /**\n * @type {import('@themost/data').ODataModelBuilder}\n */\n const builder = app.getService(ODataModelBuilder);\n if (builder) {\n builder.clean(true);\n }\n // extend universis api scope access configuration\n if (app && app.container) {\n app.container.subscribe((container) => {\n if (container) {\n // add extra scope access elements\n const scopeAccess = app.getConfiguration().getStrategy(function ScopeAccessConfiguration() {\n });\n if (scopeAccess != null) {\n scopeAccess.elements.unshift(...WebHookScopeAccessElements);\n }\n }\n });\n }\n\n // configure logger\n // get options from configuration\n const options = Object.assign({\n logLevel: 'info',\n logFormat: 'raw',\n logDir: path.join(process.cwd(), 'log')\n }, app.getConfiguration().getSourceAt('settings/universis/webhooks'));\n const logDir = options.logDir ? path.resolve(options.logDir) : path.join(process.cwd(), 'log');\n const logFile = 'webhooks.log';\n // create a rotating write stream\n // noinspection JSValidateTypes\n const logStream = createStream(logFile, {\n interval: '1d', // rotate daily\n path: logDir\n });\n this.logger = new JsonLogger({\n level: options.logLevel,\n format: options.logFormat,\n stdout: logStream,\n stderr: logStream\n });\n this.logger.info(`Universis WebHookService initialized with log level \"${options.logLevel}\"`);\n\n if (app) {\n const self = this;\n setTimeout(() => {\n (async () => {\n await self.refresh();\n })();\n }, 1000);\n }\n\n }\n\n /**\n * Refresh web hook actions\n * @returns {Promise<void>}\n */\n async refresh() {\n /**\n * @type {import('@themost/data').DataContext}\n */\n let context;\n try {\n // noinspection JSUnresolvedReference\n context = this.getApplication().createContext();\n this.logger.info('Registering existing web hook actions');\n const items = await context.model('WebHookAction').asQueryable().take(-1).silent().getAllItems();\n if (items.length > 0) {\n this.logger.info(`Found ${items.length} web hook action(s). The operation will automatically register event listeners to the underlying data models.`);\n }\n for (const item of items) {\n const model = context.model(item.about);\n if (model) {\n await new Promise((resolve, reject) => {\n afterSave({ state: DataObjectState.Insert, target: item, model}, (err) => {\n if (err) {\n return reject(err);\n }\n return resolve();\n });\n });\n } else {\n this.logger.warn(`Cannot register web hook action with name \"${item.name || 'unknown'}\" because model \"${item.about}\" does not exist.`);\n }\n }\n } catch(err) {\n this.logger.error('An error occurred when registering existing web hooks');\n this.logger.error(err);\n } finally {\n if (context) {\n await context.finalizeAsync()\n }\n }\n }\n\n /**\n *\n * @param {import('@themost/data').DataModel} model\n * @param {*} target\n * @param {string} filter\n * @param {number} state\n * @returns {Promise<boolean>}\n */\n async filterObjectAsync(model, target, filter, state) {\n const parser = new DataModelFilterParser(model);\n const { $expand, $where } = await parser.parseAsync(filter)\n const q = new DataQueryable(model);\n Object.assign(q.query, {\n $where,\n $expand\n });\n const { primaryKey } = model;\n const id = target[primaryKey];\n q.prepare();\n if (state !== DataObjectState.Delete) {\n q.where(primaryKey).equal(id);\n }\n const exists = await q.count();\n return (exists > 0);\n }\n\n /**\n * Emit web hook events\n * @param {import('@themost/data').DataEventArgs} event\n * @param {{action?: string, emit?: boolean}} extraArgs\n */\n emit(event, extraArgs) {\n const context = event.model.context;\n // get previous and current state of the entity\n const { previous, target, state, model } = event;\n /**\n * @type {import('@themost/express').ExpressDataApplication|import('@themost/common').ApplicationBase}\n */\n const application = context.application;\n // noinspection JSUnresolvedReference\n /**\n * @type {import('@themost/express').ExpressDataContext|import('@themost/data').DataContext}\n */\n const newContext = application.createContext();\n const about = model.name;\n const self = this;\n (async function() {\n // noinspection JSUnresolvedReference\n const q = newContext.model('WebHook').asQueryable().where((x, about, state) => {\n // noinspection JSBitwiseOperatorUsage\n return (x.action.about === about) && (x.action.state === state) && (x.active === true);\n }, about, state).select((x) => {\n return {\n id: x.id,\n config: x.config,\n action: x.action,\n about: x.action.about,\n emit: x.emit,\n username: x.owner.name,\n filter: x.action.filter,\n when: x.action.when\n }\n }).silent().take(25).skip(0);\n // apply extra arguments for finding web hooks\n const findArgs = Object.assign({ emit: true }, extraArgs || {});\n q.prepare();\n Object.keys(findArgs).forEach((key) => {\n const value = findArgs[key];\n q.query.$where ? q.and(key).equal(value) : q.where(key).equal(value);\n });\n\n const { viewAdapter: WebHooks } = newContext.model('WebHook');\n const targetModel = newContext.model(about);\n // get entity set\n const builder = application.getService(ODataModelBuilder);\n const entitySet = builder.getEntityTypeEntitySet(targetModel.name)\n const { primaryKey: key } = targetModel;\n // get origin\n const origin = context.getConfiguration().getSourceAt('settings/universis/api/origin');\n /**\n * @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\n */\n let list = await q.getList();\n if (list.total > 0) {\n while (list.total >= (list.skip + list.value.length)) {\n for (const item of list.value) {\n // set context user\n newContext.user = {\n name: item.username || 'anonymous'\n }\n try {\n let send = true;\n if (state === DataObjectState.Insert) {\n // validate the current state of a new object\n const filter = item.when || item.filter;\n send = await self.filterObjectAsync(targetModel, target, filter, state);\n } else {\n // validate previous state\n send = await self.filterObjectAsync(targetModel, previous, item.when, state);\n // validate current state\n if (send && item.filter) {\n if (state === DataObjectState.Delete) {\n send = await self.filterObjectAsync(targetModel, previous, item.filter, state);\n } else {\n send = await self.filterObjectAsync(targetModel, target, item.filter, state);\n }\n }\n }\n if (send) {\n self.logger.info(`Sending web hook for model \"${about}\" to url \"${item.config.url}\"`);\n // send web hook request\n const result = await request('post', item.config.url)\n .set('Content-Type', item.config.contentType)\n .send({\n event: item.action,\n entityType: targetModel.name,\n entitySet: entitySet && entitySet.name,\n origin: origin,\n target: {\n id: (state === DataObjectState.Insert) ? target[key] : previous[key],\n }\n });\n const lastResponse = {\n status: result.status\n };\n self.logger.info(`Web hook for model \"${about}\" to url ${item.config.url} returned status ${result.status}`);\n // update last response with an ad-hoc query\n await newContext.db.executeAsync(\n new QueryExpression().update(WebHooks).set({\n lastResponse: JSON.stringify(lastResponse),\n }).where('id').equal(item.id)\n , []);\n } else {\n self.logger.debug(`Web hook for model \"${about}\" and object with identifier ${target[key]} to url \"${item.config.url}\" was filtered and not sent`);\n }\n } catch (err) {\n self.logger.error(`Error sending web hook for model \"${about}\" to url \"${item.config.url}\"`);\n self.logger.error(err);\n }\n }\n list = await q.take(25).skip(list.skip + list.value.length);\n }\n }\n })();\n }\n\n}\n\nexport {\n WebHookService\n}"],"mappings":";;AAEA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,KAAA,GAAAF,OAAA;;;;;;AAMA,IAAAG,aAAA,GAAAH,OAAA;AACA,IAAAI,WAAA,GAAAC,sBAAA,CAAAL,OAAA;AACA,IAAAM,MAAA,GAAAN,OAAA;AACA,IAAAO,WAAA,GAAAP,OAAA;AACA,IAAAQ,KAAA,GAAAH,sBAAA,CAAAL,OAAA;AACA,IAAAS,mBAAA,GAAAT,OAAA;AACA,IAAAU,gBAAA,GAAAV,OAAA;AACA,IAAAW,gBAAA,GAAAX,OAAA,gCAAwD,SAAAK,uBAAAO,CAAA,UAAAA,CAAA,IAAAA,CAAA,CAAAC,UAAA,GAAAD,CAAA,KAAAE,OAAA,EAAAF,CAAA,KAjBxD;;AAmBA,MAAMG,cAAc,SAASC,0BAAkB,CAAC;EAC5CC,WAAWA,CAACC,GAAG,EAAE;IACb,KAAK,CAACA,GAAG,CAAC;IACV;AACR;AACA;IACQ,MAAMC,YAAY,GAAGD,GAAG,CAACE,gBAAgB,CAAC,CAAC,CAACC,WAAW,CAACC,0BAAoB,CAAC;IAC7EH,YAAY,CAACI,OAAO,CAACC,IAAI,CAAC,IAAIC,0BAAY,CAACP,GAAG,CAACE,gBAAgB,CAAC,CAAC,CAAC,CAAC;IACnE;AACR;AACA;IACQ,MAAMM,OAAO,GAAGR,GAAG,CAACS,UAAU,CAACC,uBAAiB,CAAC;IACjD,IAAIF,OAAO,EAAE;MACTA,OAAO,CAACG,KAAK,CAAC,IAAI,CAAC;IACvB;IACA;IACA,IA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AC,MAAM;gBACHtC,IAAI,CAACP,MAAM,CAACkG,KAAK,CAAC,uBAAuB7E,KAAK,gCAAgCO,MAAM,CAAC0C,GAAG,CAAC,YAAYlD,IAAI,CAAC0C,MAAM,CAACsB,GAAG,6BAA6B,CAAC;cACtJ;YACJ,CAAC,CAAC,OAAOvD,GAAG,EAAE;cACVtB,IAAI,CAACP,MAAM,CAACgC,KAAK,CAAC,qCAAqCX,KAAK,aAAaD,IAAI,CAAC0C,MAAM,CAACsB,GAAG,GAAG,CAAC;cAC5F7E,IAAI,CAACP,MAAM,CAACgC,KAAK,CAACH,GAAG,CAAC;YAC1B;UACJ;UACAkD,IAAI,GAAG,MAAMtC,CAAC,CAACzB,IAAI,CAAC,EAAE,CAAC,CAACkD,IAAI,CAACa,IAAI,CAACb,IAAI,GAAGa,IAAI,CAACR,KAAK,CAACpD,MAAM,CAAC;QAC/D;MACJ;IACJ,CAAC,EAAE,CAAC;EACR;;AAEJ,CAACgF,OAAA,CAAAzI,cAAA,GAAAA,cAAA","ignoreList":[]}
1
+ {"version":3,"file":"WebHookService.js","names":["_common","require","_scope","_data","_superagent","_interopRequireDefault","_query","_jsonLogger","_path","_rotatingFileStream","_dataModelFilter","_OnWebHookAction","e","__esModule","default","WebHookService","ApplicationService","constructor","app","container","subscribe","scopeAccess","getConfiguration","getStrategy","ScopeAccessConfiguration","elements","unshift","WebHookScopeAccessElements","options","Object","assign","logLevel","logFormat","logDir","path","join","process","cwd","getSourceAt","resolve","logFile","logStream","createStream","interval","logger","JsonLogger","level","format","stdout","stderr","info","self","setTimeout","refresh","context","getApplication","createContext","items","model","asQueryable","take","silent","getAllItems","length","item","about","Promise","reject","afterSave","state","DataObjectState","Insert","target","err","warn","name","error","finalizeAsync","filterObjectAsync","filter","parser","DataModelFilterParser","$expand","$where","parseAsync","q","DataQueryable","query","primaryKey","id","prepare","Delete","where","equal","exists","count","emit","event","extraArgs","previous","application","newContext","x","action","active","select","config","username","owner","when","skip","findArgs","keys","forEach","key","value","and","viewAdapter","WebHooks","targetModel","builder","getService","ODataModelBuilder","entitySet","getEntityTypeEntitySet","origin","list","getList","total","user","send","url","result","request","set","contentType","entityType","lastResponse","status","db","executeAsync","QueryExpression","update","JSON","stringify","debug","exports"],"sources":["../src/WebHookService.js"],"sourcesContent":["// noinspection NpmUsedModulesInstalled\n\nimport {ApplicationService} from '@themost/common';\nimport {WebHookScopeAccessElements} from './config/scope.access';\nimport {\n DataObjectState,\n DataQueryable,\n ODataModelBuilder,\n} from '@themost/data';\nimport request from 'superagent';\nimport {QueryExpression} from '@themost/query';\nimport { JsonLogger } from '@themost/json-logger';\nimport path from 'path';\nimport { createStream } from 'rotating-file-stream';\nimport {DataModelFilterParser} from '@themost/data/data-model-filter.parser';\nimport { afterSave } from './listeners/OnWebHookAction';\n\nclass WebHookService extends ApplicationService {\n constructor(app) {\n super(app);\n if (app && app.container) {\n app.container.subscribe((container) => {\n if (container) {\n // add extra scope access elements\n const scopeAccess = app.getConfiguration().getStrategy(function ScopeAccessConfiguration() {\n });\n if (scopeAccess != null) {\n scopeAccess.elements.unshift(...WebHookScopeAccessElements);\n }\n }\n });\n }\n // configure logger\n // get options from configuration\n const options = Object.assign({\n logLevel: 'info',\n logFormat: 'raw',\n logDir: path.join(process.cwd(), 'log')\n }, app.getConfiguration().getSourceAt('settings/universis/webhooks'));\n const logDir = options.logDir ? path.resolve(options.logDir) : path.join(process.cwd(), 'log');\n const logFile = 'webhooks.log';\n // create a rotating write stream\n // noinspection JSValidateTypes\n const logStream = createStream(logFile, {\n interval: '1d', // rotate daily\n path: logDir\n });\n this.logger = new JsonLogger({\n level: options.logLevel,\n format: options.logFormat,\n stdout: logStream,\n stderr: logStream\n });\n this.logger.info(`Universis WebHookService initialized with log level \"${options.logLevel}\"`);\n\n if (app) {\n const self = this;\n setTimeout(() => {\n (async () => {\n await self.refresh();\n })();\n }, 1000);\n }\n\n }\n\n /**\n * Refresh web hook actions\n * @returns {Promise<void>}\n */\n async refresh() {\n /**\n * @type {import('@themost/data').DataContext}\n */\n let context;\n try {\n // noinspection JSUnresolvedReference\n context = this.getApplication().createContext();\n this.logger.info('Registering existing web hook actions');\n const items = await context.model('WebHookAction').asQueryable().take(-1).silent().getAllItems();\n if (items.length > 0) {\n this.logger.info(`Found ${items.length} web hook action(s). The operation will automatically register event listeners to the underlying data models.`);\n }\n for (const item of items) {\n const model = context.model(item.about);\n if (model) {\n await new Promise((resolve, reject) => {\n afterSave({ state: DataObjectState.Insert, target: item, model}, (err) => {\n if (err) {\n return reject(err);\n }\n return resolve();\n });\n });\n } else {\n this.logger.warn(`Cannot register web hook action with name \"${item.name || 'unknown'}\" because model \"${item.about}\" does not exist.`);\n }\n }\n } catch(err) {\n this.logger.error('An error occurred when registering existing web hooks');\n this.logger.error(err);\n } finally {\n if (context) {\n await context.finalizeAsync()\n }\n }\n }\n\n /**\n *\n * @param {import('@themost/data').DataModel} model\n * @param {*} target\n * @param {string} filter\n * @param {number} state\n * @returns {Promise<boolean>}\n */\n async filterObjectAsync(model, target, filter, state) {\n const parser = new DataModelFilterParser(model);\n const { $expand, $where } = await parser.parseAsync(filter)\n const q = new DataQueryable(model);\n Object.assign(q.query, {\n $where,\n $expand\n });\n const { primaryKey } = model;\n const id = target[primaryKey];\n q.prepare();\n if (state !== DataObjectState.Delete) {\n q.where(primaryKey).equal(id);\n }\n const exists = await q.count();\n return (exists > 0);\n }\n\n /**\n * Emit web hook events\n * @param {import('@themost/data').DataEventArgs} event\n * @param {{action?: string, emit?: boolean}} extraArgs\n */\n emit(event, extraArgs) {\n const context = event.model.context;\n // get previous and current state of the entity\n const { previous, target, state, model } = event;\n /**\n * @type {import('@themost/express').ExpressDataApplication|import('@themost/common').ApplicationBase}\n */\n const application = context.application;\n // noinspection JSUnresolvedReference\n /**\n * @type {import('@themost/express').ExpressDataContext|import('@themost/data').DataContext}\n */\n const newContext = application.createContext();\n const about = model.name;\n const self = this;\n (async function() {\n // noinspection JSUnresolvedReference\n const q = newContext.model('WebHook').asQueryable().where((x, about, state) => {\n // noinspection JSBitwiseOperatorUsage\n return (x.action.about === about) && (x.action.state === state) && (x.active === true);\n }, about, state).select((x) => {\n return {\n id: x.id,\n config: x.config,\n action: x.action,\n about: x.action.about,\n emit: x.emit,\n username: x.owner.name,\n filter: x.action.filter,\n when: x.action.when\n }\n }).silent().take(25).skip(0);\n // apply extra arguments for finding web hooks\n const findArgs = Object.assign({ emit: true }, extraArgs || {});\n q.prepare();\n Object.keys(findArgs).forEach((key) => {\n const value = findArgs[key];\n q.query.$where ? q.and(key).equal(value) : q.where(key).equal(value);\n });\n\n const { viewAdapter: WebHooks } = newContext.model('WebHook');\n const targetModel = newContext.model(about);\n // get entity set\n const builder = application.getService(ODataModelBuilder);\n const entitySet = builder.getEntityTypeEntitySet(targetModel.name)\n const { primaryKey: key } = targetModel;\n // get origin\n const origin = context.getConfiguration().getSourceAt('settings/universis/api/origin');\n /**\n * @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\n */\n let list = await q.getList();\n if (list.total > 0) {\n while (list.total >= (list.skip + list.value.length)) {\n for (const item of list.value) {\n // set context user\n newContext.user = {\n name: item.username || 'anonymous'\n }\n try {\n let send = true;\n if (state === DataObjectState.Insert) {\n // validate the current state of a new object\n const filter = item.when || item.filter;\n send = await self.filterObjectAsync(targetModel, target, filter, state);\n } else {\n // validate previous state\n send = await self.filterObjectAsync(targetModel, previous, item.when, state);\n // validate current state\n if (send && item.filter) {\n if (state === DataObjectState.Delete) {\n send = await self.filterObjectAsync(targetModel, previous, item.filter, state);\n } else {\n send = await self.filterObjectAsync(targetModel, target, item.filter, state);\n }\n }\n }\n if (send) {\n self.logger.info(`Sending web hook for model \"${about}\" to url \"${item.config.url}\"`);\n // send web hook request\n const result = await request('post', item.config.url)\n .set('Content-Type', item.config.contentType)\n .send({\n event: item.action,\n entityType: targetModel.name,\n entitySet: entitySet && entitySet.name,\n origin: origin,\n target: {\n id: (state === DataObjectState.Insert) ? target[key] : previous[key],\n }\n });\n const lastResponse = {\n status: result.status\n };\n self.logger.info(`Web hook for model \"${about}\" to url ${item.config.url} returned status ${result.status}`);\n // update last response with an ad-hoc query\n await newContext.db.executeAsync(\n new QueryExpression().update(WebHooks).set({\n lastResponse: JSON.stringify(lastResponse),\n }).where('id').equal(item.id)\n , []);\n } else {\n self.logger.debug(`Web hook for model \"${about}\" and object with identifier ${target[key]} to url \"${item.config.url}\" was filtered and not sent`);\n }\n } catch (err) {\n self.logger.error(`Error sending web hook for model \"${about}\" to url \"${item.config.url}\"`);\n self.logger.error(err);\n }\n }\n list = await q.take(25).skip(list.skip + list.value.length);\n }\n }\n })();\n }\n\n}\n\nexport {\n WebHookService\n}"],"mappings":";;AAEA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AACA,IAAAE,KAAA,GAAAF,OAAA;;;;;AAKA,IAAAG,WAAA,GAAAC,sBAAA,CAAAJ,OAAA;AACA,IAAAK,MAAA,GAAAL,OAAA;AACA,IAAAM,WAAA,GAAAN,OAAA;AACA,IAAAO,KAAA,GAAAH,sBAAA,CAAAJ,OAAA;AACA,IAAAQ,mBAAA,GAAAR,OAAA;AACA,IAAAS,gBAAA,GAAAT,OAAA;AACA,IAAAU,gBAAA,GAAAV,OAAA,gCAAwD,SAAAI,uBAAAO,CAAA,UAAAA,CAAA,IAAAA,CAAA,CAAAC,UAAA,GAAAD,CAAA,KAAAE,OAAA,EAAAF,CAAA,KAfxD;;AAiBA,MAAMG,cAAc,SAASC,0BAAkB,CAAC;EAC5CC,WAAWA,CAACC,GAAG,EAAE;IACb,KAAK,CAACA,GAAG,CAAC;IACV,IAAIA,GAAG,IAAIA,GAAG,CAACC,SAAS,EAAE;MACtBD,GAAG,CAACC,SAAS,CAACC,SAAS,CAAC,CAACD,SAAS,KAAK;QACnC,IAAIA,SAAS,EAAE;UACX;UACA,MAAME,WAAW,GA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,CAAC;cACtJ;YACJ,CAAC,CAAC,OAAO1D,GAAG,EAAE;cACVtB,IAAI,CAACP,MAAM,CAACgC,KAAK,CAAC,qCAAqCX,KAAK,aAAaD,IAAI,CAAC0C,MAAM,CAACyB,GAAG,GAAG,CAAC;cAC5FhF,IAAI,CAACP,MAAM,CAACgC,KAAK,CAACH,GAAG,CAAC;YAC1B;UACJ;UACAqD,IAAI,GAAG,MAAMzC,CAAC,CAACzB,IAAI,CAAC,EAAE,CAAC,CAACkD,IAAI,CAACgB,IAAI,CAAChB,IAAI,GAAGgB,IAAI,CAACX,KAAK,CAACpD,MAAM,CAAC;QAC/D;MACJ;IACJ,CAAC,EAAE,CAAC;EACR;;AAEJ,CAACmF,OAAA,CAAAnI,cAAA,GAAAA,cAAA","ignoreList":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@universis/webhooks",
3
- "version": "1.2.0",
3
+ "version": "1.2.4",
4
4
  "description": "Universis Webhooks API Library",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -32,7 +32,7 @@
32
32
  "peerDependencies": {
33
33
  "@themost/common": "^2",
34
34
  "@themost/data": "^2",
35
- "@themost/express": "^1",
35
+ "@themost/express": "^2",
36
36
  "@themost/query": "^2",
37
37
  "@themost/xml": "^2"
38
38
  },
@@ -6,9 +6,7 @@ import {
6
6
  DataObjectState,
7
7
  DataQueryable,
8
8
  ODataModelBuilder,
9
- SchemaLoaderStrategy
10
9
  } from '@themost/data';
11
- import {SchemaLoader} from './SchemaLoader';
12
10
  import request from 'superagent';
13
11
  import {QueryExpression} from '@themost/query';
14
12
  import { JsonLogger } from '@themost/json-logger';
@@ -20,19 +18,6 @@ import { afterSave } from './listeners/OnWebHookAction';
20
18
  class WebHookService extends ApplicationService {
21
19
  constructor(app) {
22
20
  super(app);
23
- /**
24
- * @type {import('@themost/data').DefaultSchemaLoaderStrategy}
25
- */
26
- const schemaLoader = app.getConfiguration().getStrategy(SchemaLoaderStrategy);
27
- schemaLoader.loaders.push(new SchemaLoader(app.getConfiguration()));
28
- /**
29
- * @type {import('@themost/data').ODataModelBuilder}
30
- */
31
- const builder = app.getService(ODataModelBuilder);
32
- if (builder) {
33
- builder.clean(true);
34
- }
35
- // extend universis api scope access configuration
36
21
  if (app && app.container) {
37
22
  app.container.subscribe((container) => {
38
23
  if (container) {
@@ -45,7 +30,6 @@ class WebHookService extends ApplicationService {
45
30
  }
46
31
  });
47
32
  }
48
-
49
33
  // configure logger
50
34
  // get options from configuration
51
35
  const options = Object.assign({
package/.gitlab-ci.yml DELETED
@@ -1,40 +0,0 @@
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/jest.config.js DELETED
@@ -1,202 +0,0 @@
1
- /**
2
- * For a detailed explanation regarding each configuration property, visit:
3
- * https://jestjs.io/docs/configuration
4
- */
5
-
6
- /** @type {import('jest').Config} */
7
- const config = {
8
- // All imported modules in your tests should be mocked automatically
9
- // automock: false,
10
-
11
- // Stop running tests after `n` failures
12
- // bail: 0,
13
-
14
- // The directory where Jest should store its cached dependency information
15
- // cacheDirectory: "/private/var/folders/bs/w3b1f9k16kb7mm17d66vdmwc0000gn/T/jest_dx",
16
-
17
- // Automatically clear mock calls, instances, contexts and results before every test
18
- // clearMocks: false,
19
-
20
- // Indicates whether the coverage information should be collected while executing the test
21
- // collectCoverage: false,
22
-
23
- // An array of glob patterns indicating a set of files for which coverage information should be collected
24
- // collectCoverageFrom: undefined,
25
-
26
- // The directory where Jest should output its coverage files
27
- // coverageDirectory: undefined,
28
-
29
- // An array of regexp pattern strings used to skip coverage collection
30
- // coveragePathIgnorePatterns: [
31
- // "/node_modules/"
32
- // ],
33
-
34
- // Indicates which provider should be used to instrument code for coverage
35
- coverageProvider: "v8",
36
-
37
- // A list of reporter names that Jest uses when writing coverage reports
38
- // coverageReporters: [
39
- // "json",
40
- // "text",
41
- // "lcov",
42
- // "clover"
43
- // ],
44
-
45
- // An object that configures minimum threshold enforcement for coverage results
46
- // coverageThreshold: undefined,
47
-
48
- // A path to a custom dependency extractor
49
- // dependencyExtractor: undefined,
50
-
51
- // Make calling deprecated APIs throw helpful error messages
52
- // errorOnDeprecated: false,
53
-
54
- // The default configuration for fake timers
55
- // fakeTimers: {
56
- // "enableGlobally": false
57
- // },
58
-
59
- // Force coverage collection from ignored files using an array of glob patterns
60
- // forceCoverageMatch: [],
61
-
62
- // A path to a module which exports an async function that is triggered once before all test suites
63
- // globalSetup: undefined,
64
-
65
- // A path to a module which exports an async function that is triggered once after all test suites
66
- // globalTeardown: undefined,
67
-
68
- // A set of global variables that need to be available in all test environments
69
- // globals: {},
70
-
71
- // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
72
- // maxWorkers: "50%",
73
-
74
- // An array of directory names to be searched recursively up from the requiring module's location
75
- // moduleDirectories: [
76
- // "node_modules"
77
- // ],
78
-
79
- // An array of file extensions your modules use
80
- // moduleFileExtensions: [
81
- // "js",
82
- // "mjs",
83
- // "cjs",
84
- // "jsx",
85
- // "ts",
86
- // "mts",
87
- // "cts",
88
- // "tsx",
89
- // "json",
90
- // "node"
91
- // ],
92
-
93
- // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
94
- moduleNameMapper: {
95
- '@universis/webhooks': '<rootDir>/src',
96
- },
97
-
98
- // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
99
- // modulePathIgnorePatterns: [],
100
-
101
- // Activates notifications for test results
102
- // notify: false,
103
-
104
- // An enum that specifies notification mode. Requires { notify: true }
105
- // notifyMode: "failure-change",
106
-
107
- // A preset that is used as a base for Jest's configuration
108
- // preset: undefined,
109
-
110
- // Run tests from one or more projects
111
- // projects: undefined,
112
-
113
- // Use this configuration option to add custom reporters to Jest
114
- // reporters: undefined,
115
-
116
- // Automatically reset mock state before every test
117
- // resetMocks: false,
118
-
119
- // Reset the module registry before running each individual test
120
- // resetModules: false,
121
-
122
- // A path to a custom resolver
123
- // resolver: undefined,
124
-
125
- // Automatically restore mock state and implementation before every test
126
- // restoreMocks: false,
127
-
128
- // The root directory that Jest should scan for tests and modules within
129
- // rootDir: undefined,
130
-
131
- // A list of paths to directories that Jest should use to search for files in
132
- // roots: [
133
- // "<rootDir>"
134
- // ],
135
-
136
- // Allows you to use a custom runner instead of Jest's default test runner
137
- // runner: "jest-runner",
138
-
139
- // The paths to modules that run some code to configure or set up the testing environment before each test
140
- // setupFiles: [],
141
-
142
- // A list of paths to modules that run some code to configure or set up the testing framework before each test
143
- // setupFilesAfterEnv: [],
144
-
145
- // The number of seconds after which a test is considered as slow and reported as such in the results.
146
- // slowTestThreshold: 5,
147
-
148
- // A list of paths to snapshot serializer modules Jest should use for snapshot testing
149
- // snapshotSerializers: [],
150
-
151
- // The test environment that will be used for testing
152
- // testEnvironment: "jest-environment-node",
153
-
154
- // Options that will be passed to the testEnvironment
155
- // testEnvironmentOptions: {},
156
-
157
- // Adds a location field to test results
158
- // testLocationInResults: false,
159
-
160
- // The glob patterns Jest uses to detect test files
161
- // testMatch: [
162
- // "**/__tests__/**/*.?([mc])[jt]s?(x)",
163
- // "**/?(*.)+(spec|test).?([mc])[jt]s?(x)"
164
- // ],
165
-
166
- // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
167
- // testPathIgnorePatterns: [
168
- // "/node_modules/"
169
- // ],
170
-
171
- // The regexp pattern or array of patterns that Jest uses to detect test files
172
- // testRegex: [],
173
-
174
- // This option allows the use of a custom results processor
175
- // testResultsProcessor: undefined,
176
-
177
- // This option allows use of a custom test runner
178
- // testRunner: "jest-circus/runner",
179
-
180
- // A map from regular expressions to paths to transformers
181
- // transform: undefined,
182
-
183
- // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
184
- // transformIgnorePatterns: [
185
- // "/node_modules/",
186
- // "\\.pnp\\.[^\\/]+$"
187
- // ],
188
-
189
- // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
190
- // unmockedModulePathPatterns: undefined,
191
-
192
- // Indicates whether each individual test should be reported during the run
193
- // verbose: undefined,
194
-
195
- // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
196
- // watchPathIgnorePatterns: [],
197
-
198
- // Whether to use watchman for file crawling
199
- // watchman: true,
200
- };
201
-
202
- module.exports = config;
package/jsconfig.json DELETED
@@ -1,8 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "baseUrl": ".",
4
- "paths": {
5
- "@universis/webhooks": ["./src"]
6
- }
7
- }
8
- }