This repository has been archived by the owner on Nov 23, 2022. It is now read-only.
forked from tetrasmolyn/relish
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
78 lines (59 loc) · 1.89 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'use strict'
const Hoek = require('hoek')
const internals = {}
internals.defaults = {
stripQuotes: false,
messages: {}
}
const Relish = function Relish (opts) {
this.exports = {}
this._opts = opts ? Hoek.applyToDefaults(internals.defaults, opts) : internals.defaults
this.parseError = (error) => {
return error.details.map((i) => {
let err = {
key: i.context.key,
path: i.path.join('.'),
message: this._opts.stripQuotes ? i.message.replace(/"/g, '') : i.message,
type: i.type.split('.').shift(),
constraint: i.type.split('.').pop()
}
// if label is different than key, provide label
if (i.context.label !== err.key) {
err.label = i.context.label
}
// set custom message (if exists)
if (this._opts.messages.hasOwnProperty(err.path)) {
err.message = this._opts.messages[err.path]
} else if (this._opts.messages.hasOwnProperty(err.key)) {
err.message = this._opts.messages[err.key]
}
return err
})
}
this.formatResponse = (error, source, errorMessage, errors) => {
// append errors array to response
error.output.payload.message = errorMessage
error.output.payload.validation = {
source: source,
errors: errors
}
return error
}
this.exports.options = (opts) => {
this._opts = Hoek.applyToDefaults(this._opts, opts)
return this.exports
}
this.exports.failAction = (request, h, err) => {
// parse error object
const errors = this.parseError(err)
// build main error message
const errorMessage = errors.map((e) => e.message).join(', ')
// retrieve validation failure source
const source = err.output.payload.validation.source
// format error response
err = this.formatResponse(err, source, errorMessage, errors)
return err
}
return this.exports
}
module.exports = (opts) => new Relish(opts)