zodern:relay is a new package for type safe Meteor methods and publications. It allows you to easily write schemas for methods and publications, and typescript will:
- provide types for the method and publication parameters
- validate the types of the arguments when calling the method or publication
- provide the correct type for the method result
To use it for methods, you create your methods in files in methods
directories:
import { createMethod } from 'meteor/zodern:relay';
import { z } from 'zod';
export const add = createMethod({
name: 'add',
schema: z.number().array().length(2),
run([a, b]) {
return a + b;
},
});
Then, on the client you import the method and call it:
import { add } from '/imports/methods/add';
add([1, 2]).then(result => {
console.log(result); // logs 3
});
Typescript provides the types for the run
function’s parameter based on the schema, makes sure the types when calling add
are correct, and uses the return type of the run function as the type for the method’s result.
It works very similarily for publications. You use createPublication
in files in publications
directories, and export a function to subscribe to the publication:
import { createPublication } from 'meteor/zodern:relay';
import { z } from 'zod';
import { Projects } from '/collections';
export const subscribeProject = createPublication({
name: 'project',
schema: z.object({
id: z.string()
}),
run({ id }) {
return Projects.find({ _id: id });
},
});
Files in the methods
and publications
directories are treated specially. On the server they are left as is. For the client, their content is completely replaced so you don’t have to worry about exposing server code. Instead, on the client they export small functions to call any methods or subscribe to any publications that were originally exported.
More details are in the readme.
Credit
This uses a similar approach to @blitz/rpc. I found it on Monday, and thought something similar could work for Meteor.