mion uses @mionkit/run-types for automatic validation.
This is a powerful type system that extracts TypeScript type metadata at compile time and uses it at runtime.
No need to manage schemas or write extra code for validation.
All routes and middleFns parameters are automatically validated before the method gets called.
If validation fails, an RpcError is thrown with details about the validation errors and method gets never called.
import {Routes, route} from '@mionkit/router';
import {memoryStoreService} from './full-example.app.ts';
// Your TypeScript types ARE the validation schema
interface User {
id: string;
email: string;
age: number;
birthDate: Date;
tags: Set<string>;
}
type NewUser = Omit<User, 'id'>;
// mion automatically:
// 1. Restores Date and Set from JSON
// 2. Validates user parameter
const routes = {
createUser: route((ctx, user: NewUser): User => {
// user is already validated and types are restored
console.log(user.birthDate instanceof Date); // true
console.log(user.tags instanceof Set); // true
return memoryStoreService.createUser(user);
}),
} satisfies Routes;
If an invalid request is sent, a ValidationError (which extends RpcError) is thrown:
import {RpcError} from '@mionkit/core';
import {RunTypeError, ValidationError} from '@mionkit/run-types';
// Example validation error thrown when invalid data is received
const validationError: ValidationError = new RpcError({
statusCode: 400,
type: 'validation-error',
publicMessage: "Invalid params in 'createUser', validation failed.",
errorData: {
typeErrors: [
{path: 'email', expected: 'string'},
{path: 'age', expected: 'number'},
],
},
});
mion provides two main validation functions with different use cases:
isType is optimized for performance and returns a simple true or false result. Use this when you only need to know if data is valid without detailed error information.
import {isType} from '@mionkit/run-types';
interface User {
name: string;
email: string;
age: number;
}
const data = {name: 'John', email: 'john@example.com', age: 30};
if (isType<User>(data)) {
// data is valid, proceed with confidence
console.log('Valid user:', data.name);
} else {
// data is invalid, handle error
console.log('Invalid user data');
}
When to use isType:
getTypeErrors returns comprehensive error data including the path to invalid properties and expected types. Use this when you need to provide detailed feedback to users or for debugging.
import {getTypeErrors} from '@mionkit/run-types';
interface User {
name: string;
email: string;
age: number;
}
const invalidData = {name: 'John', email: 123, age: 'twenty'};
const errors = getTypeErrors<User>(invalidData);
if (errors.length > 0) {
// errors contains detailed information:
// [
// { path: 'email', expected: 'string' },
// { path: 'age', expected: 'number' }
// ]
errors.forEach((err) => {
console.log(`Field '${err.path}': expected ${err.expected}`);
});
}
When to use getTypeErrors: