Skip to content

Commit

Permalink
chore: refactor binary coercion and add some tests
Browse files Browse the repository at this point in the history
Follow-up to #2960
  • Loading branch information
Marsup committed Aug 27, 2023
1 parent 4e03f19 commit 4274f62
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 12 deletions.
20 changes: 8 additions & 12 deletions lib/types/binary.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,16 @@ module.exports = Any.extend({

type: 'binary',

coerce(value, { schema }) {
coerce: {
from: ['string', 'object'],
method(value, { schema }) {

if (typeof value === 'string') {
try {
return { value: Buffer.from(value, schema._flags.encoding) };
}
catch (ignoreErr) { }
}

if (typeof value === 'object' && value !== null && value.type === 'Buffer') {
try {
return { value: Buffer.from(value, schema._flags.encoding) };
if (typeof value === 'string' || (value !== null && value.type === 'Buffer')) {
try {
return { value: Buffer.from(value, schema._flags.encoding) };
}
catch (ignoreErr) { }
}
catch (ignoreErr) { }
}
},

Expand Down
24 changes: 24 additions & 0 deletions test/types/binary.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,30 @@ describe('binary', () => {
]);
});

it('returns an error when malformed JSON object is used', () => {

Helper.validate(Joi.binary(), [
[{ foo: 'bar' }, false, {
message: '"value" must be a buffer or a string',
path: [],
type: 'binary.base',
context: { label: 'value', value: { foo: 'bar' } }
}],
[null, false, {
message: '"value" must be a buffer or a string',
path: [],
type: 'binary.base',
context: { label: 'value', value: null }
}],
[{ type: 'Buffer' }, false, {
message: '"value" must be a buffer or a string',
path: [],
type: 'binary.base',
context: { label: 'value', value: { type: 'Buffer' } }
}]
]);
});

it('returns an error when a JSON encoded & decoded buffer object is used in strict mode', () => {

// Generate Buffer and stringify it as JSON.
Expand Down

0 comments on commit 4274f62

Please sign in to comment.