b3ee41e11948cdb4d0f5ba053932619e0b1df5a7542045a416a31fe7aeb3d5d211f1aaa652ec792b2603a1c76d1e3870eb53200783a665224507b4e392b054-exec 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. 'use strict';
  2. const Hoek = require('@hapi/hoek');
  3. const Any = require('../any');
  4. const internals = {};
  5. internals.Binary = class extends Any {
  6. constructor() {
  7. super();
  8. this._type = 'binary';
  9. }
  10. _base(value, state, options) {
  11. const result = {
  12. value
  13. };
  14. if (typeof value === 'string' &&
  15. options.convert) {
  16. try {
  17. result.value = Buffer.from(value, this._flags.encoding);
  18. }
  19. catch (e) { }
  20. }
  21. result.errors = Buffer.isBuffer(result.value) ? null : this.createError('binary.base', null, state, options);
  22. return result;
  23. }
  24. encoding(encoding) {
  25. Hoek.assert(Buffer.isEncoding(encoding), 'Invalid encoding:', encoding);
  26. if (this._flags.encoding === encoding) {
  27. return this;
  28. }
  29. const obj = this.clone();
  30. obj._flags.encoding = encoding;
  31. return obj;
  32. }
  33. min(limit) {
  34. Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer');
  35. return this._test('min', limit, function (value, state, options) {
  36. if (value.length >= limit) {
  37. return value;
  38. }
  39. return this.createError('binary.min', { limit, value }, state, options);
  40. });
  41. }
  42. max(limit) {
  43. Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer');
  44. return this._test('max', limit, function (value, state, options) {
  45. if (value.length <= limit) {
  46. return value;
  47. }
  48. return this.createError('binary.max', { limit, value }, state, options);
  49. });
  50. }
  51. length(limit) {
  52. Hoek.assert(Number.isSafeInteger(limit) && limit >= 0, 'limit must be a positive integer');
  53. return this._test('length', limit, function (value, state, options) {
  54. if (value.length === limit) {
  55. return value;
  56. }
  57. return this.createError('binary.length', { limit, value }, state, options);
  58. });
  59. }
  60. };
  61. module.exports = new internals.Binary();