loopback-readonly-mixin

1.0.5 • Public • Published

READONLY

Circle CI Coverage Status Dependencies

This module is designed for the Strongloop Loopback framework. It provides a mixin that makes it possible to mark models or model properties as read only. A read only property may not be written to directly when creating or updating models using remote REST methods.

The property value is an object that details model properties to be treated as readonly properties. Each key in the object must match a property name defined for the model.

A feature requests exists against the Loopback project for similar functionality in core: https://github.com/strongloop/loopback/issues/531

INSTALL

npm install --save loopback-readonly-mixin

MIXINSOURCES

With loopback-boot@v2.8.0 mixinSources have been implemented in a way which allows for loading this mixin without changes to the server.js file previously required.

Add the mixins property to your server/model-config.json like the following:

{
  "_meta": {
    "sources": [
      "loopback/common/models",
      "loopback/server/models",
      "../common/models",
      "./models"
    ],
    "mixins": [
      "loopback/common/mixins",
      "../node_modules/loopback-readonly-mixin",
      "../common/mixins"
    ]
  }
}

CONFIG

To use with your Models add the mixins attribute to the definition object of your model config.

  {
    "name": "Widget",
    "properties": {
      "name": {
        "type": "string",
      }
    },
    "mixins": {
      "ReadOnly" : {
        "only": ["name"]
      }
    }
  }
  {
    "name": "Widget",
    "properties": {
      "name": {
        "type": "string",
      },
      "title": {
        "type": "string",
      }
    },
    "mixins": {
      "ReadOnly" : {
        "except": ["name"] // title is read-only
      }
    }
  }

Attempting to update a ReadOnly model will reult in a 403 error.

OPTIONS

The specific fields that are to be marked as readonly can be set by passing an object to the mixin options.

In this example we mark the status and role fields as readonly.

  {
    "name": "Widget",
    "properties": {
      "name": {
        "type": "string",
      },
      "status": {
        "type": "string",
      },
      "role": {
        "type": "string",
      }
    },
    "mixins": {
      "ReadOnly" : {
        "except": ["name"]
      }
    }
  }

Any data set by a REST client in ReadOnly properties will be stripped out on the way to the server and will not be saved on the updated model instance.

TESTING

Run the tests in test.js

  npm test

Run with debugging output on:

  DEBUG='loopback-ds-readonly-mixin' npm test

Package Sidebar

Install

npm i loopback-readonly-mixin

Weekly Downloads

5

Version

1.0.5

License

MIT

Last publish

Collaborators

  • hoangphuc