Meteor-Community-Packages / meteor-collection2

A Meteor package that extends Mongo.Collection to provide support for specifying a schema and then validating against that schema when inserting and updating.
https://packosphere.com/aldeed/collection2
MIT License
1.02k stars 108 forks source link

Best way to have different client and server schemas #397

Closed Floriferous closed 4 years ago

Floriferous commented 4 years ago

I'd like to attach a autoValue function to one field of my schema, but only on the server, as it is pure server-side logic. What is the cleanest way to do this?

Something like this:

// Shared env
const schema = new SimpleSchema()

// Client
MyCollection.attachSchema(schema)

// Server
schema.myField.autoValue = function() {
  // Do server stuff
}
MyCollection.attachSchema(schema)
Floriferous commented 4 years ago

So using attachSchema multiple times is the right trick, the only annoying part was that you have to define the type multiple times. If instead of passing a SimpleSchema you just pass an object, it works:

So, here's a scaleable solution to do this across collections:

const addServerSideSchema = (collection, extendedSchema) => {
  const schema = collection.simpleSchema();
  collection.attachSchema(schema.extend(extendedSchema));
  return collection;
}

// And then:
const Todos = new Mongo.Collection('todos');

// On both environments
Todos.attachSchema( ... )

// On the server, for example:
addServerSideSchema(Todos, {
  userId: {
    autoValue() {
      if (this.isSet) {
        notifySlackOfUserChange(this.value);
      }
    }
  }
})