Last active
January 4, 2024 20:34
-
-
Save aidanbon/5ba4bf2c59486a0f61b32ae75a1d4bcc to your computer and use it in GitHub Desktop.
Enhance Avro to support data validation via Regular Expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Enhance Avro to support data validation via Regular Expression | |
*/ | |
const avro = require('avsc') | |
class ValidatedString extends avro.types.LogicalType { | |
constructor (attrs, opts) { | |
super(attrs, opts) | |
this._pattern = new RegExp(attrs.pattern) | |
} | |
_toValue (val) { | |
if (!this._pattern.test(val)) { | |
throw new Error('invalid string: ' + val) | |
} | |
return val | |
} | |
} | |
const type = avro.parse({ | |
name: 'Example', | |
type: 'record', | |
fields: [ | |
{ | |
name: 'custId', | |
type: 'string' // Normal (free-form) string. | |
}, | |
{ | |
name: 'sessionId', | |
type: { | |
type: 'string', | |
logicalType: 'validated-string', | |
pattern: '^[0-9]{4}-[0-9]{2}$' // Validation pattern. | |
} | |
}, | |
] | |
}, {logicalTypes: {'validated-string': ValidatedString}}) | |
// tests | |
console.log(type.isValid({custId: 'abc', sessionId: '1234-12'})) // true | |
console.log(type.isValid({custId: 'abc', sessionId: 'foobar'})) // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment