Skip to content

Commit

Permalink
fix: do not store computed properties
Browse files Browse the repository at this point in the history
  • Loading branch information
Tom Kirkpatrick committed Sep 5, 2017
1 parent 4f85ebf commit 9d684ee
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
db.json
coverage
.nyc_output
16 changes: 16 additions & 0 deletions lib/computed.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
}
30 changes: 28 additions & 2 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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, {
Expand Down Expand Up @@ -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')
})
})
})

0 comments on commit 9d684ee

Please sign in to comment.