SierraSoftworks / Iridium

A high performance MongoDB ORM for Node.js
http://sierrasoftworks.github.io/Iridium/
Other
570 stars 25 forks source link

Bug: Plugin Validators Not Being Registered #119

Open CatGuardian opened 6 years ago

CatGuardian commented 6 years ago

Hi Benjamin,

A long while back I asked you about how to automatically do a createdAt and updatedAt property for all of my Models and you suggested a Plugin that looks something like the following (the point is to look at the public validate portion):

import { Changes, Instance, Model, Plugin } from 'iridium';
import * as Skmatc from 'skmatc';

export class CreatedUpdatedPlugin implements Plugin {
  public newModel(model: Model<any, any>): void {
    Object.assign(model.schema, {
      createdAt: 'readonly',
      updatedAt: 'readonly',
    });

    const oldOnCreating = model.hooks.onCreating;
    model.hooks.onCreating = async (doc: any) => {
      oldOnCreating && await Promise.resolve(oldOnCreating(doc));

      doc.createdAt = new Date();
      doc.updatedAt = new Date();
    };

    const oldOnSaving = model.hooks.onSaving;
    model.hooks.onSaving = async (instance: Instance<any, any>, changes: Changes) => {
      oldOnSaving && await Promise.resolve(oldOnSaving(instance, changes));

      if (changes) {
        changes.$currentDate = Object.assign(changes.$currentDate || {}, {
          updatedAt: true,
        });
      }
    };
  }

  public validate = [
    Skmatc.create((schema) => {
      return schema === 'readonly';
    }, function (schema, data, path) {
      return this.fail('no changes allowed');
    }),
  ];
}

But it turns out that the public validate thing isn't being utilized by Iridium anywhere.

I'll have a Pull Request out shortly.