From 9d684eec1dfc5f05353882e374f5731bf779767c Mon Sep 17 00:00:00 2001 From: Tom Kirkpatrick Date: Tue, 5 Sep 2017 09:53:54 +0200 Subject: [PATCH] fix: do not store computed properties --- .gitignore | 1 + lib/computed.js | 16 ++++++++++++++++ test/test.js | 30 ++++++++++++++++++++++++++++-- 3 files changed, 45 insertions(+), 2 deletions(-) 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') + }) + }) })