Skip to content

Commit

Permalink
feat: support bindary buffer that has been JSON.parse(JSON.strinified())
Browse files Browse the repository at this point in the history
  • Loading branch information
kassah authored and Marsup committed Aug 27, 2023
1 parent 55c3f6a commit 4e03f19
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
12 changes: 9 additions & 3 deletions lib/types/binary.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,16 @@ module.exports = Any.extend({

type: 'binary',

coerce: {
from: 'string',
method(value, { schema }) {
coerce(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) };
}
Expand Down
29 changes: 29 additions & 0 deletions test/types/binary.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,18 @@ describe('binary', () => {
expect(value.toString('utf8')).to.equal('test');
});

it('converts a JSON encoded and decoded buffer to a buffer', () => {

const testPngMagicNumber = Buffer.from('89504E470D0A', 'hex');
const jsonEncodedBuffer = JSON.stringify(testPngMagicNumber);
const jsonDecodedBuffer = JSON.parse(jsonEncodedBuffer);

const value = Joi.binary().validate(jsonDecodedBuffer).value;
expect(value instanceof Buffer).to.equal(true);
expect(value.length).to.equal(testPngMagicNumber.length);
expect(value).to.equal(testPngMagicNumber);
});

it('validates allowed buffer content', () => {

const hello = Buffer.from('hello');
Expand Down Expand Up @@ -120,6 +132,23 @@ describe('binary', () => {
]);
});

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

// Generate Buffer and stringify it as JSON.
const testPngMagicNumber = Buffer.from('89504E470D0A', 'hex');
const jsonEncodedBuffer = JSON.stringify(testPngMagicNumber);
const jsonDecodedBuffer = JSON.parse(jsonEncodedBuffer);

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

it('accepts a buffer object', () => {

Helper.validate(Joi.binary(), [
Expand Down

0 comments on commit 4e03f19

Please sign in to comment.