Skip to content

Plugins

Steffen Droppelmann edited this page Jul 29, 2021 · 3 revisions

Plugin

A plugin can be used to supply systems with a set of constraints and functions. The idea behind this is that you define them once, and then add them to multiple systems, in order to reduce redundancy. If you have multiple different model types that have the same field, name for example, you can define a plugin that only has name constraints, which can then be used across multiple systems. Similarly, you can define a plugin that comes with a certain set of functions that can be used by multiple systems. Here is how you define a plugin:

// This is our plugin model type
type HasName = {
    name: string;
};

// Person model with a name
type Person = {
    name: string;
    lastName: string;
};

// Animal model with a name
type Animal = {
    name: string;
    legs: number;
};

// In our plugin, we can define anything that has to do with the name property
class NamePlugin extends ConSys.Plugin<HasName, {}> {
    async registerConstraints(system: ConSys.ConstraintSystem<HasName, {}>): Promise<void> {
        system.addConstraint({
            constraint: "ALWAYS: LENGTH($name) > 4"
        });
    }

    async registerFunctions(system: ConSys.ConstraintSystem<HasName, {}>): Promise<void> {
        system.addFunction("LENGTH", (str: string) => {
            return str.length;
        });
    }
}

// Person instance
let person: Person = {
    name: "Bruce",
    lastName: "Wayne"
};

// Animal instance
let animal: Animal = {
    name: "Flash",
    legs: 4
};

// These are our different systems
const personConstraints = new ConSys.ConstraintSystem<Person, {}>();
const animalConstraints = new ConSys.ConstraintSystem<Animal, {}>();

const namePlugin = new NamePlugin();

// We can register our plugin to both of them
await personConstraints.registerPlugin(namePlugin);
await animalConstraints.registerPlugin(namePlugin);

Clone this wiki locally