Skip to content

Commit

Permalink
feat: add error handling to hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
eduardoboucas committed Nov 4, 2016
1 parent 9817b73 commit f4a2988
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 6 deletions.
39 changes: 35 additions & 4 deletions dadi/lib/model/hook.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
var path = require('path')
var config = require(path.join(__dirname, '/../../../config'))
'use strict'

const path = require('path')
const config = require(path.join(__dirname, '/../../../config'))

/**
* Creates a new hook. Allowed types:
Expand All @@ -17,15 +19,28 @@ var config = require(path.join(__dirname, '/../../../config'))
* @return Hook
* @api public
*/
var Hook = function (data, type) {
const Hook = function (data, type) {
if (typeof data === 'string') {
this.name = data
} else {
this.name = data.hook
this.options = data.options
}

this.hook = this.load()
this.hook = function () {
let result

try {
const hookFn = this.load()

result = hookFn.apply(this, arguments)
} catch (error) {
result = Promise.reject(error)
}

return result
}.bind(this)

this.type = type
}

Expand Down Expand Up @@ -98,6 +113,22 @@ Hook.prototype.apply = function () {
return false
}

/**
* Returns the name of the hook
*
* @return String
* @api public
*/
Hook.prototype.getName = function () {
return this.name
}

/**
* Loads the hook file
*
* @return Hook module
* @api public
*/
Hook.prototype.load = function () {
return require(require('path').resolve(config.get('paths.hooks')) + '/' + this.name)
}
Expand Down
8 changes: 6 additions & 2 deletions dadi/lib/model/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ var ObjectID = require('mongodb').ObjectID
var path = require('path')

var connection = require(path.join(__dirname, '/connection'))
var formatError = require('@dadi/format-error')
var Validator = require(path.join(__dirname, '/validator'))
var History = require(path.join(__dirname, '/history'))
var Composer = require(path.join(__dirname, '/../composer')).Composer
Expand Down Expand Up @@ -209,8 +210,11 @@ Model.prototype.create = function (obj, internals, done, req) {

Promise.resolve(hook.apply(current, this.schema, this.name, req)).then((newDoc) => {
callback((newDoc === null) ? {} : null, newDoc)
}).catch((err) => {
callback(err)
}).catch(err => {
callback([formatError.createApiError('0002', {
hookName: hook.getName(),
errorMessage: err
})])
})
}, (err, result) => {
processedDocs++
Expand Down

0 comments on commit f4a2988

Please sign in to comment.