| 13 | * Buffer (binary) type |
| 14 | */ |
| 15 | export class BufferType implements Type<Buffer> { |
| 16 | readonly name = 'buffer'; |
| 17 | |
| 18 | isInstance(value: any) { |
| 19 | return value == null || Buffer.isBuffer(value); |
| 20 | } |
| 21 | |
| 22 | defaultValue() { |
| 23 | return Buffer.from([]); |
| 24 | } |
| 25 | |
| 26 | isCoercible(value: any): boolean { |
| 27 | if (value == null) return true; |
| 28 | if (typeof value === 'string') return true; |
| 29 | if (Buffer.isBuffer(value)) return true; |
| 30 | if (Array.isArray(value)) return true; |
| 31 | return false; |
| 32 | } |
| 33 | |
| 34 | coerce(value: any, options?: Options) { |
| 35 | if (value == null) return value; |
| 36 | if (Buffer.isBuffer(value)) return value as Buffer; |
| 37 | if (typeof value === 'string') { |
| 38 | options = options ?? {}; |
| 39 | const encoding = options.encoding || 'utf-8'; |
| 40 | return Buffer.from(value, encoding); |
| 41 | } else if (Array.isArray(value)) { |
| 42 | return Buffer.from(value); |
| 43 | } |
| 44 | const msg = util.format('Invalid %s: %j', this.name, value); |
| 45 | throw new TypeError(msg); |
| 46 | } |
| 47 | |
| 48 | serialize(value: Buffer | null | undefined, options?: Options) { |
| 49 | if (value == null) return value; |
| 50 | const encoding = options?.encoding || 'base64'; |
| 51 | return value.toString(encoding); |
| 52 | } |
| 53 | } |
nothing calls this directly
no outgoing calls
no test coverage detected