As I can see, many Meteor developers use SimpleSchema
for data validation.
SimpleSchema
is great, but it’s a little bit complicated. Usually you can just use Meteor’s check
library. It’s very simple, allows you to create your own data types and keeps your code flat.
https://docs.meteor.com/api/check.html
I was using Meteor for about two years, but discovered the greatness of check
library just a month ago. So maybe there are other Meteor developers who still haven’t payed enough attention to check
.
See how cool it is:
import { Mongo } from 'meteor/mongo';
import { Match, check } from 'meteor/check';
const Albums = new Mongo.Collection('albums');
// helpers
const URL_REGEXP = /^https?:\/\/[\w\d.-_/]+\/?&/;
const Optional = Match.Optional;
const isString = (s) => Match.test(s, String);
// data types
const NonEmptyString = Match.Where((s) => isString(s) && s.length > 0);
const Url = Match.Where((s) => isString(s) && URL_REGEXP.test(s));
const Integer = Math.Integer;
// model description
const AlbumModel = {
ownerId: String,
title: NonEmptyString,
description: Optional(String),
photos: Optional([
{
caption: Optional(String),
url: Url,
size: { width: Integer, height: Integer },
}
]),
};
Meteor.methods({
createAlbum(album) {
check(album, AlbumModel);
check(album.ownerId, this.userId);
Albums.insert(album);
},
updateAlbumTitle(albumId, newTitle) {
check(newTitle, AlbumModel.title);
check(Albums.findOne(albumId).ownerId, this.userId);
Albums.update(albumId, { $set: { title: newTitle } });
},
});