Skip to content

Advanced: Creating a Plugin

If you create a lot of custom types and validators for your project, you can bundle them into a single, reusable Plugin. A plugin is just an object with an install method.

javascript
// my-custom-plugin.js
const MyCustomPlugin = {
  install(manager) { // The 'manager' object has .addType and .addValidator
    manager.addType('csv', context => {
        if (context.value === undefined || context.value === null) return [];
        if (typeof context.value !== 'string') context.throwTypeError();
        return context.value.split(',').map(item => item.trim());
    });
    
    manager.addValidator('slug', context => {
        const slugRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
        if (typeof context.value !== 'string' || !slugRegex.test(context.value)) {
            context.throwParamError('INVALID_SLUG', 'Value must be a valid slug.');
        }
    });
  }
};

export default MyCustomPlugin;

// in your main app file:
import { createSchema } from 'json-rest-schema';
import MyCustomPlugin from './my-custom-plugin.js';

// Install all your custom rules in one line!
createSchema.use(MyCustomPlugin);

// Now 'slug' and 'csv' are available to all schemas.
const mySchema = createSchema({
  tags: { type: 'csv' },
  pageUrl: { type: 'string', slug: true }
});

This makes your custom rules portable and keeps your main application setup clean.


GPL-3.0-only