GithubHelp home page GithubHelp logo

fullcube / loopback-ds-readonly-mixin Goto Github PK

View Code? Open in Web Editor NEW
51.0 15.0 19.0 171 KB

A mixin to enable readonly properties for loopback Models

License: MIT License

JavaScript 100.00%
loopback loopback-mixin lb2 mit fullcube

loopback-ds-readonly-mixin's Introduction

READONLY

Greenkeeper badge

Circle CI Coverage Status Dependencies semantic-release

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: strongloop/loopback#531

INSTALL

npm install --save loopback-ds-readonly-mixin

MIXINSOURCES

With [email protected] 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-ds-readonly-mixin/lib",
      "../common/mixins"
    ]
  }
}

SERVER.JS

In your server/server.js file add the following line before the boot(app, __dirname); line.

...
var app = module.exports = loopback();
...
// Add ReadOnly Mixin to loopback
require('loopback-ds-readonly-mixin')(app);

boot(app, __dirname, function(err) {
  'use strict';
  if (err) throw err;

  // start the server if `$ node server.js`
  if (require.main === module)
    app.start();
});

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" : true
    }
  }

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" : {
        "status" : true,
        "role" : true
      }
    }
  }

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:mixin:readonly' npm test

loopback-ds-readonly-mixin's People

Contributors

greenkeeper[bot] avatar mrbatista avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

loopback-ds-readonly-mixin's Issues

An in-range update of loopback is breaking the build 🚨

The devDependency loopback was updated from 3.24.2 to 3.25.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

loopback is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ ci/circleci: Your tests failed on CircleCI (Details).

Commits

The new version differs by 3 commits.

  • 1e33ec5 3.25.0
  • c38900b Merge pull request #4119 from studykik/fix/appdynamics-proxy
  • edb8dbc Support middleware injected by AppDynamics.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

update is required for this mixin to work with loopback 3

the mixin does not currently handle the new loopback 3 methods patchAttributes and replaceById, this could easily be updated by adding the following code:

  // loopback 3
  Model.beforeRemote('prototype.patchAttributes', function(ctx, modelInstance, next) {
      Model.stripReadOnlyProperties(ctx, modelInstance, next);
  });
  Model.beforeRemote('replaceById', function(ctx, modelInstance, next) {
    Model.stripReadOnlyProperties(ctx, modelInstance, next);
  });

"loopback": "3.0.0"

getting error TypeError: Cannot convert undefined or null to object when starting application

In my model below the properties I have:

"mixins": {
      "ReadOnly" : {
        "entered" : true,
        "dbkey" : true
      }
    }

and when I run the application I get:

$ node .
/Users/jas/loopback/hts/node_modules/loopback-ds-readonly-mixin/lib/read-only.js:96
    Object.keys(Model.definition.settings.relations).forEach(relationName => {
           ^

TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at EventEmitter.Model.on (/Users/jas/loopback/hts/node_modules/loopback-ds-readonly-mixin/lib/read-only.js:96:12)
    at emitOne (events.js:96:13)
    at EventEmitter.emit (events.js:188:7)
    at Function.app.model (/Users/jas/loopback/hts/node_modules/loopback/lib/application.js:162:9)
    at /Users/jas/loopback/hts/node_modules/loopback-boot/lib/executor.js:203:9
    at Array.forEach (native)
    at setupModels (/Users/jas/loopback/hts/node_modules/loopback-boot/lib/executor.js:199:23)
    at execute (/Users/jas/loopback/hts/node_modules/loopback-boot/lib/executor.js:40:3)
    at bootLoopBackApp (/Users/jas/loopback/hts/node_modules/loopback-boot/index.js:154:3)
    at Object.<anonymous> (/Users/jas/loopback/hts/server/server.js:23:1)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)

Is this a bug, or am I just missing something ?
I am using:

    "loopback": "^3.19.0",
    "loopback-boot": "^2.6.5",
    "loopback-component-explorer": "^6.0.0",
    "loopback-connector-mssql": "^2.9.0",
    "loopback-ds-readonly-mixin": "^2.0.4",

I commented out the part about updates via relationship, and it now does not choke. However, when I try to insert a record using a PUT, and leave out readonly fields (because they are provided by the database) I get:

mdsdev4:hts jas$ node .
Web server listening at: http://localhost:3000
Browse your REST API at http://localhost:3000/explorer
Unhandled error for request POST /api/Runs?access_token=heyhey: ValidationError: The `Runs` instance is not valid. Details: `username` can't be blank (value: undefined); `entered` can't be blank (value: undefined); `dbkey` can't be blank (value: undefined).

An in-range update of supertest is breaking the build 🚨

Version 3.3.0 of supertest was just published.

Branch Build failing 🚨
Dependency supertest
Current Version 3.2.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

supertest is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ ci/circleci: Your tests failed on CircleCI (Details).

Release Notes v3.3.0

#509 - Fix #486, bug in _assertBody, switch to deepStrictEqual (thanks @mikelax)
#510 - Refactor test files to use const/let (thanks @rimiti)

Commits

The new version differs by 10 commits.

  • e910e85 chore: Prepare for v3.3.0 release.
  • bd864de Merge pull request #511 from visionmedia/bugfix-486-equal
  • 101fbf5 Merge branch 'master' into bugfix-486-equal
  • 04230bb Merge pull request #510 from visionmedia/refact-const-let
  • 510a7ae bugfix: 486 Change method to use deepStrictEqual. (#509)
  • 913150d chore(.editorconfig) [*.md] block removed
  • 82e0828 refact(test/supertest.js) vars replaced by const and let
  • 5443136 chore(.editorconfig) configuration file created
  • 7233ba6 chore(.eslintrc) parserOptions option added to use es6
  • 322ebf6 bugfix: 486 Change method to use deepStrictEqual.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Is this working with related model inserts?

Hi,
I suspect that this won't work if the model is updated through a relationship, as the beforeRemote hook won't intercept updates in methods such as Model.prototype.__update__<relation>

I think that if that is true it should be mentioned in the documentation :)

mixinSource docs are wrong/misleading?

Hey - we upgraded to [email protected] and changed our loopback-ds-readonly-mixin config to avoid the deprecation warning. After doing so, the mixin stopped working. I believe your docs are wrong - the mixin source needs to reference the lib subdir, like this:

    "mixins": [
      "loopback/common/mixins",
      "../node_modules/loopback-ds-readonly-mixin/lib",
      "../common/mixins"
    ]

Once we changed that the mixin started loading again.

Getting error starting loopback 2 on 1.1.0

Getting the following with 1.1.0. Solved this by reverting back to 1.0.1

C:\sites\rtview-cloud-api\node_modules\loopback-ds-readonly-mixin\lib\read-only.js:65
    Object.keys(Model.definition.settings.relations).forEach(relationName => {
           ^

TypeError: Cannot convert undefined or null to object
    at EventEmitter.<anonymous> (C:\sites\rtview-cloud-api\node_modules\loopback-ds-readonly-mixin\lib\read-only.js:65:12)
    at emitOne (events.js:101:20)
    at EventEmitter.emit (events.js:188:7)
    at EventEmitter.app.model (C:\sites\rtview-cloud-api\node_modules\loopback\lib\application.js:170:9)
    at C:\sites\rtview-cloud-api\node_modules\loopback-boot\lib\executor.js:202:9
    at Array.forEach (native)
    at setupModels (C:\sites\rtview-cloud-api\node_modules\loopback-boot\lib\executor.js:198:23)
    at execute (C:\sites\rtview-cloud-api\node_modules\loopback-boot\lib\executor.js:39:3)
    at bootLoopBackApp (C:\sites\rtview-cloud-api\node_modules\loopback-boot\index.js:154:3)
    at Object.<anonymous> (C:\sites\rtview-cloud-api\server\server.js:50:1)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\lang\\nodejs\\node.exe" "C:\\lang\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v6.9.4
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! [email protected] start: `node .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script 'node .'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the rtview-cloud-api package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node .
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs rtview-cloud-api
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls rtview-cloud-api
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\sites\rtview-cloud-api\npm-debug.log

Only validates once when using a mocha watcher

Hi,
great mixin, but I noticed that it does not handle reloads.
I use mocha -w when writing tests. I enabled the debug output for the mixin and have a test to verify it's functionality within our own test suite.
The first time always works, but if the tests re-run (due to file changes) it will not re-apply the mixin. There is also not debug output.
I think mocha uses the caching for npm modules.

Not sure whether this is a loopback issue (mixin loading) or can get solved here.

Notice: I use the model-config.json method for loading the mixin as stated in this issue #4

Causes SQL errors when only readonly properties are specified

I marked a property modified as read only in my model and went to test it by executing PUT {"modified": 1} but it threw SQL errors. After enabling DEBUG on the mysql connector I realized it just removed the column set in the statement but then the query was invalid:

loopback:connector:mysql SQL: UPDATEtasksSET WHEREid=?, params: [1]

As you can see there are no columns being SET in between SET and WHERE.

An in-range update of mocha is breaking the build 🚨

Version 3.4.0 of mocha just got published.

Branch Build failing 🚨
Dependency mocha
Current Version 3.3.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As mocha is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ ci/circleci Your tests failed on CircleCI Details

Release Notes v3.4.0

Mocha is now moving to a quicker release schedule: when non-breaking changes are merged, a release should happen that week.

This week's highlights:

  • allowUncaught added to commandline as --allow-uncaught (and bugfixed)
  • warning-related Node flags

πŸŽ‰ Enhancements

πŸ› Fixes

πŸ”© Other

Commits

The new version differs by 9 commits0.

  • 7554b31 Add Changelog for v3.4.0
  • 9f7f7ed Add --trace-warnings flag
  • 92561c8 Add --no-warnings flag
  • ceee976 lint test/integration/fixtures/simple-reporter.js
  • dcfc094 Revert "use semistandard directly"
  • 93392dd no special case for macOS running Karma locally
  • 4d1d91d --allow-uncaught cli option
  • fb1e083 fix allowUncaught in browser
  • 4ed3fc5 Add license report and scan status

false

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Deprecation Warnings & LB3

Recent versions of the Loopback 2.x versions have introduced deprecation warnings, which the readme does not seem to address.

When running under LB 3.X, I get a "Model not found: mixins" error when the application boots.
Also a warning: " warning: you are using async-hook which is unstable."

Is this module compatible with LB 3.X? Am I missing something with regards to handling these deprecation warnings?

edit: I found the cause of my 'Model not found: mixins' error. It was mis-placement on my part in the model-config.json file.

However, now all my models throw errors: Model "XYZ" uses unknown mixin: Readonly

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.