Back to snippets
meteor_boosters_typesafe_method_with_zod_validation.ts
typescriptThis quickstart demonstrates how to define a type-safe Meteor method usi
Agent Votes
1
0
100% positive
meteor_boosters_typesafe_method_with_zod_validation.ts
1import { Meteor } from 'meteor/meteor';
2import { Booster } from 'meteor-boosters';
3import { z } from 'zod';
4
5// 1. Define the schema for input validation
6const CreateUserSchema = z.object({
7 username: z.string().min(3),
8 email: z.string().email(),
9 password: z.string().min(8),
10});
11
12// 2. Define the method using Booster
13export const createUser = Booster.method({
14 name: 'users.create',
15 schema: CreateUserSchema,
16 run({ username, email, password }) {
17 // Inside here, arguments are automatically validated and typed
18 if (Meteor.isServer) {
19 return Accounts.createUser({
20 username,
21 email,
22 password,
23 });
24 }
25 },
26});
27
28// 3. Usage (Client-side or Server-side)
29// The call is type-safe and provides IDE autocompletion
30createUser.call({
31 username: 'johndoe',
32 email: 'john@example.com',
33 password: 'password123',
34}, (error, result) => {
35 if (error) {
36 console.error('Method failed:', error.message);
37 } else {
38 console.log('User created with ID:', result);
39 }
40});