Ghost/core/server/services/webhooks/webhooks-service.js
Daniel Lockyer 86680cb207 Updated knex dependency
refs https://github.com/TryGhost/Toolbox/issues/213

- our `knex` dependency has been out of date for a while so my aim was
  to bring it up to date
- this required also switching `sqlite3` to `@vscode/sqlite3` because
  knex switched the default sqlite driver
- this commit also bumps knex-migrator and switches to a mock-knex fork
  until Knex 1.0 support has been merged
- also updates an error message to handle a new code in SQLite
2022-03-30 08:47:57 +01:00

60 lines
1.9 KiB
JavaScript

const {ValidationError} = require('@tryghost/errors');
const tpl = require('@tryghost/tpl');
const messages = {
webhookAlreadyExists: 'Target URL has already been used for this event.',
nonExistingIntegrationIdProvided: {
message: `Validation failed for '{key}'.`,
context: `'integration_id' value does not match any existing integration.`,
help: `Provide the 'integration_id' of an existing integration.`
}
};
class WebhooksService {
constructor({WebhookModel}) {
this.WebhookModel = WebhookModel;
}
async add(data, options) {
const webhook = await this.WebhookModel.getByEventAndTarget(
data.webhooks[0].event,
data.webhooks[0].target_url,
options
);
if (webhook) {
throw new ValidationError({
message: messages.webhookAlreadyExists
});
}
try {
const newWebhook = await this.WebhookModel.add(data.webhooks[0], options);
return newWebhook;
} catch (error) {
if (error.errno === 1452
|| (error.code === 'SQLITE_CONSTRAINT' && /SQLITE_CONSTRAINT: FOREIGN KEY constraint failed/.test(error.message))
|| (error.code === 'SQLITE_CONSTRAINT_FOREIGNKEY')) {
throw new ValidationError({
message: tpl(messages.nonExistingIntegrationIdProvided.message, {
key: 'integration_id'
}),
context: messages.nonExistingIntegrationIdProvided.context,
help: messages.nonExistingIntegrationIdProvided.help
});
}
throw error;
}
}
}
/**
* @returns {WebhooksService} instance of the PostsService
*/
const getWebhooksServiceInstance = ({WebhookModel}) => {
return new WebhooksService({WebhookModel});
};
module.exports = getWebhooksServiceInstance;