Skip to content
This repository has been archived by the owner on Jun 20, 2022. It is now read-only.

Commit

Permalink
fix: custom validation error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
juliangoacher committed Feb 13, 2020
1 parent 32a1365 commit ea71b09
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 12 deletions.
11 changes: 10 additions & 1 deletion packages/trail-hapi-plugin/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,16 @@ const formatReasons = function (error) {
for (const reason of get(error, 'data.details', [])) {
// Gather informations and try to assign a message
const attribute = reason.path.join('.')
let message = errorsMessages[reason.type]

let message
// Check for nested reason from alternatives.
if (reason.type === 'alternatives.match') {
const type = get(reason,'context.details.1.context.error.type')
message = errorsMessages[type]
}
else {
message = errorsMessages[reason.type]
}

// We found a message, add to the output
if (message) reasons[attribute] = message
Expand Down
19 changes: 9 additions & 10 deletions packages/trail-hapi-plugin/lib/schemas/trails.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,15 @@ const stringOrObject = function (name) {
Joi.string()
.description(`${name} id`)
.example(name)
.required()
.error(errors => {
const value = get(errors, '0.context.value')

// The value is object, ignore all the errors here
if (typeof value === 'object' && !Array.isArray(value)) return {}
// Overwrite message for invalid type
return {type: 'custom.stringOrObject'}
.error(() => {
const type = 'custom.stringOrObject'
const err = new Error(type)
err.type = type
return err
})
).example(name)
)
.required()
.example(name)
}

const dateTime = Joi.string()
Expand Down Expand Up @@ -117,7 +116,7 @@ const trailSchema = {
.description('A audit trail')
.meta({id: 'models/trail.request'})
.keys({
when: dateTime,
when: dateTime,
who: stringOrObject('Trail actor'),
what: stringOrObject('Trail subject'),
subject: stringOrObject('Trail target'),
Expand Down
2 changes: 1 addition & 1 deletion packages/trail-hapi-plugin/test/routes/trails.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ describe('Trails REST operations', () => {
reasons: {
meta: errorsMessages['object.base'],
subject: errorsMessages['any.required'],
'what.id': errorsMessages['any.required'],
what: errorsMessages['custom.stringOrObject'],
when: errorsMessages['string.isoDate'],
who: errorsMessages['custom.stringOrObject']
}
Expand Down

0 comments on commit ea71b09

Please sign in to comment.