typed:model

v0.0.5Published last year

Meteor Typed Model

A Zod validated, type safe wraper around Meteor Mongo Collections.

Package Status

This package is currently a WIP. Documentation is incomplete and there are no automated tests. That being said, the code is reliable and has been extracted from the JollyRoger project.

Installation

Install typed:model and zod:

meteor add typed:model
meteor npm install zod

Usage

Basic Usage

1import { Model, CustomTypes, SchemaHelpers } from 'meteor/typed:model';
2import type { ModelType } from 'meteor/typed:model';
3import { z } from 'zod';
4
5const { nonEmptyString } = CustomTypes;
6const { withCommon } = SchemaHelpers;
7
8const Link = withCommon(
9  z.object({
10    title: nonEmptyString,
11    url: z.string().url(),
12  })
13);
14
15export const LinkModel = new Model({
16  name: 'links',
17  schema: Link,
18});
19export type LinkType = ModelType<typeof LinkModel>;
20
21LinkModel.insert({ title: 'Google', url: 'https://google.com' });
22
23// Find a link by title and limit the fields returned to just the title.
24// Notice that the return type is properly inferred to only have a title and
25// and no other extraneous fields as you would have with a normal Meteor collection.
26const foundLink = LinkModel.findOneAsync({ title: 'Google' }, { fields: { title: 1 } });

Usage With Existing Collection

1import { Model } from 'meteor/typed:model';
2import type { ModelType } from 'meteor/typed:model';
3import { z } from 'zod';
4
5const User = z.object({
6  // Define schema necessary to accomodate Meteor's data structure for users
7});
8
9export const UserModel = new Model({
10  name: 'users',
11  schema: User,
12  collection: Meteor.users,
13});
14export type UserType = ModelType<typeof User>;
15
16const foundUser = UserModel.findOneAsync({ _id: Meteor.userId() });

Attribution

This package is composed mostly of code extracted from the JollyRoger project created by Evan Broder.