Ghost/core/server/models/webhook.js
Rishabh Garg c638863cb9 Updated webhooks schema and add relation (#10018)
* Extended webhooks schema/model and connected with integrations

refs #9942

- Updated webhooks schema with new columns - name, integration_id, secret, last_triggered_at, api_version
- Updated webhooks and integration model to map relationships
- Updated schema hash
- Updated test utils to exclude new webhooks columns for response comparison

* Added migration script for new webhooks columns

refs #9942

- Added migration script in 2.3 to add new columns to webhooks

* Updated schema hash

* Updated maxLength for api_version in schema

* Removed concurrency value from migration script

* Added defaults for webhooks model

* Added status field to webhooks for last trigger status

* Updated schema hash

* Fixed tests with status field

* Removed concurrency value in migration script

* Cleanup

* Updated schema with new fields

 - last_triggered_status, last_triggered_error
2018-10-17 18:17:13 +07:00

78 lines
2.3 KiB
JavaScript

const Promise = require('bluebird'),
ghostBookshelf = require('./base');
let Webhook,
Webhooks;
Webhook = ghostBookshelf.Model.extend({
tableName: 'webhooks',
defaults() {
return {
api_version: 'v2',
status: 'available'
};
},
integration() {
return this.belongsTo('Integration');
},
emitChange: function emitChange(event, options) {
const eventToTrigger = 'webhook' + '.' + event;
ghostBookshelf.Model.prototype.emitChange.bind(this)(this, eventToTrigger, options);
},
onCreated: function onCreated(model, response, options) {
model.emitChange('added', options);
},
onUpdated: function onUpdated(model, response, options) {
model.emitChange('edited', options);
},
onDestroyed: function onDestroyed(model, options) {
model.emitChange('deleted', options);
}
}, {
findAllByEvent: function findAllByEvent(event, unfilteredOptions) {
var options = this.filterOptions(unfilteredOptions, 'findAll'),
webhooksCollection = Webhooks.forge();
return webhooksCollection
.query('where', 'event', '=', event)
.fetch(options);
},
getByEventAndTarget: function getByEventAndTarget(event, targetUrl, unfilteredOptions) {
var options = ghostBookshelf.Model.filterOptions(unfilteredOptions, 'getByEventAndTarget');
options.require = true;
return Webhooks.forge().fetch(options).then(function then(webhooks) {
var webhookWithEventAndTarget = webhooks.find(function findWebhook(webhook) {
return webhook.get('event').toLowerCase() === event.toLowerCase()
&& webhook.get('target_url').toLowerCase() === targetUrl.toLowerCase();
});
if (webhookWithEventAndTarget) {
return webhookWithEventAndTarget;
}
}).catch(function (error) {
if (error.message === 'NotFound' || error.message === 'EmptyResponse') {
return Promise.resolve();
}
return Promise.reject(error);
});
}
});
Webhooks = ghostBookshelf.Collection.extend({
model: Webhook
});
module.exports = {
Webhook: ghostBookshelf.model('Webhook', Webhook),
Webhooks: ghostBookshelf.collection('Webhooks', Webhooks)
};