oRPC
background

Smart Conversion

Effortlessly adapt your input data to the expected type using oRPC's Smart Conversion feature.

Important: If you're using the oRPC client, you don't need this feature. The oRPC client has a built-in mechanism for handling data serialization and deserialization between the client and server, ensuring seamless type transformations.

Overview

Smart Conversion is a powerful feature in oRPC that ensures incoming string-based data is automatically transformed into the expected types based on your Zod schema. This eliminates the need for manual parsing, ensuring your application works seamlessly with correctly formatted data.

Safe and Predictable

Smart Conversion only applies transformations when:

  1. The incoming data can be converted.
  2. The schema explicitly expects the transformed type.

For example:

  • Incoming data 'true' is converted to true if the schema is z.boolean().
  • No conversion occurs if the schema is z.boolean().or(z.string()), as the input already matches the schema.

This ensures safe usage without data loss or unintended side effects.

Supported Conversions

The following types and transformations are supported:

Boolean

Strings that represent boolean values are converted as follows:

const raw = 'true'; // Input
const converted = true; // Output

Supported values:

  • 'true', 'on', 't'true
  • 'false', 'off', 'f'false

Number

Strings that can be safely parsed as numbers are converted:

const raw = '42'; // Input
const converted = 42; // Output

BigInt

Strings representing valid bigint values are transformed:

const raw = '12345678901234567890'; // Input
const converted = 12345678901234567890n; // Output

Date

Valid date strings are converted into Date objects:

const raw = '2024-11-27T00:00:00.000Z'; // Input
const converted = new Date('2024-11-27T00:00:00.000Z'); // Output

Supported formats:

  • Full ISO date-time strings (2024-11-27T00:00:00.000Z)
  • Dates only (2024-11-27)
  • Times only (19:00:00)

RegExp

Strings representing regular expressions are converted into RegExp objects:

const raw = '/^abc$/i'; // Input
const converted = /^abc$/i; // Output

URL

Valid URL strings are converted into URL objects:

const raw = 'https://example.com'; // Input
const converted = new URL('https://example.com'); // Output

Set

Arrays of items are converted into Set objects:

const raw = ['apple', 'banana', 'apple']; // Input
const converted = new Set(['apple', 'banana']); // Output

Map

Key-value pair arrays are converted into Map objects:

const raw = [
    ['key1', 'value1'],
    ['key2', 'value2']
]; // Input
 
const converted = new Map([
    ['key1', 'value1'],
    ['key2', 'value2']
]); // Output

On this page