diff --git a/.gitignore b/.gitignore index 1fd04da..66fc60c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules +db.json coverage .nyc_output diff --git a/lib/computed.js b/lib/computed.js index 4fd4a36..c1b2e45 100644 --- a/lib/computed.js +++ b/lib/computed.js @@ -42,4 +42,20 @@ module.exports = (Model, options) => { .then(value => (ctx.data[property] = value)) }) }) + + // The loaded observer is triggered when an item is loaded + Model.observe('before save', (ctx, next) => { + Object.keys(options.properties || {}).forEach(property => { + debug('Removing computed property %s', property) + + if (ctx.instance) { + ctx.instance.unsetAttribute(property) + } + if (ctx.data) { + delete ctx.data[property] + } + }) + + return next() + }) } diff --git a/test/test.js b/test/test.js index 096e893..7ea5e6b 100644 --- a/test/test.js +++ b/test/test.js @@ -11,8 +11,11 @@ const app = loopback() // import our mixin. require('../lib')(app) -// Connect to db. -const dbConnector = loopback.memory() +// Create datasource. +const dbConnector = loopback.createDataSource({ + connector: loopback.Memory, + file: 'db.json', +}) const now = new Date() @@ -49,6 +52,10 @@ describe('loopback computed property', function() { lt.beforeEach.withApp(app) + before(function() { + return Item.destroyAll() + }) + before(function(done) { new lt.TestDataBuilder() .define('itemOne', Item, { @@ -80,4 +87,23 @@ describe('loopback computed property', function() { expect(this.itemOne.promised).to.equal('Item 1: As promised I get back to you!') expect(this.itemTwo.promised).to.equal('Item 2: As promised I get back to you!') }) + + it('should not store the computed property', function() { + return this.itemOne.updateAttributes({ readonly: false }) + .then(item => { + /* eslint global-require: 0 */ + const db = require('../db.json') + const itemFromDb = JSON.parse(db.models.item[item.id]) + + expect(item).to.have.property('readonly', true) + expect(item).to.have.property('requestedAt') + expect(item).to.have.property('promised') + + expect(itemFromDb).to.have.property('id', item.id) + expect(itemFromDb).to.have.property('name', 'Item 1') + expect(itemFromDb).to.not.have.property('readonly') + expect(itemFromDb).to.not.have.property('requestedAt') + expect(itemFromDb).to.not.have.property('promised') + }) + }) })