Function: decode()
function decode(base64: string, options: EncoderOptions): Schema;Decodes a base64-encoded schema string back into a usable validation schema.
This function reverses the encoding process, decompressing and parsing the encoded schema while performing version compatibility checks. It ensures that schemas encoded with newer versions of the library are rejected to prevent runtime errors from incompatible schema formats.
The function handles:
- Base64 decoding and zlib decompression
- Version compatibility validation using semantic versioning
- Backward compatibility with legacy encoding formats
- Input validation and error handling
- Schema reconstruction using Joi's build method
Parameters
| Parameter | Type | Description |
|---|---|---|
base64 | string | The base64-encoded schema string |
options | EncoderOptions | Decoding options |
Returns
A reconstructed validation schema ready for validation
Throws
When the encoded string is not a valid schema
Throws
When the schema version is invalid or incompatible
Examples
import { decode } from "./utils";
const encodedSchema = "eJyrVkosLcmIz8nPS1WyUvJIzcnJT...";
const schema = decode(encodedSchema);
// Use the decoded schema for validation
const result = schema.validate({ name: "John", age: 30 });try {
const schema = decode(untrustedEncodedString);
// Use schema safely
} catch (error) {
if (error instanceof TypeError) {
console.error("Invalid or incompatible schema:", error.message);
}
}// Schema encoded with v2.1.0, current version is v2.0.0
const futureSchema = "..."; // Contains version 2.1.0
decode(futureSchema); // Throws: Schema version 2.1.0 is not compatible
// Schema encoded with v1.9.0, current version is v2.0.0
const oldSchema = "..."; // Contains version 1.9.0
const schema = decode(oldSchema); // Works - backward compatibleSecurity
IMPORTANT: Only decode schemas from trusted sources.
Decoded schemas may contain serialized functions that are evaluated using the Function constructor. Never decode schemas from:
- User input or user-controlled data
- Untrusted third-party APIs
- Any source you do not control
If the schema source is not under your direct control, validate its integrity using cryptographic signatures or checksums before decoding.
See
encode For encoding schemas into transportable strings