Skip to content

Commit 9d684ee

Browse files
author
Tom Kirkpatrick
committed
fix: do not store computed properties
1 parent 4f85ebf commit 9d684ee

File tree

3 files changed

+45
-2
lines changed

3 files changed

+45
-2
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
node_modules
2+
db.json
23
coverage
34
.nyc_output

lib/computed.js

+16
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,20 @@ module.exports = (Model, options) => {
4242
.then(value => (ctx.data[property] = value))
4343
})
4444
})
45+
46+
// The loaded observer is triggered when an item is loaded
47+
Model.observe('before save', (ctx, next) => {
48+
Object.keys(options.properties || {}).forEach(property => {
49+
debug('Removing computed property %s', property)
50+
51+
if (ctx.instance) {
52+
ctx.instance.unsetAttribute(property)
53+
}
54+
if (ctx.data) {
55+
delete ctx.data[property]
56+
}
57+
})
58+
59+
return next()
60+
})
4561
}

test/test.js

+28-2
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,11 @@ const app = loopback()
1111
// import our mixin.
1212
require('../lib')(app)
1313

14-
// Connect to db.
15-
const dbConnector = loopback.memory()
14+
// Create datasource.
15+
const dbConnector = loopback.createDataSource({
16+
connector: loopback.Memory,
17+
file: 'db.json',
18+
})
1619

1720
const now = new Date()
1821

@@ -49,6 +52,10 @@ describe('loopback computed property', function() {
4952

5053
lt.beforeEach.withApp(app)
5154

55+
before(function() {
56+
return Item.destroyAll()
57+
})
58+
5259
before(function(done) {
5360
new lt.TestDataBuilder()
5461
.define('itemOne', Item, {
@@ -80,4 +87,23 @@ describe('loopback computed property', function() {
8087
expect(this.itemOne.promised).to.equal('Item 1: As promised I get back to you!')
8188
expect(this.itemTwo.promised).to.equal('Item 2: As promised I get back to you!')
8289
})
90+
91+
it('should not store the computed property', function() {
92+
return this.itemOne.updateAttributes({ readonly: false })
93+
.then(item => {
94+
/* eslint global-require: 0 */
95+
const db = require('../db.json')
96+
const itemFromDb = JSON.parse(db.models.item[item.id])
97+
98+
expect(item).to.have.property('readonly', true)
99+
expect(item).to.have.property('requestedAt')
100+
expect(item).to.have.property('promised')
101+
102+
expect(itemFromDb).to.have.property('id', item.id)
103+
expect(itemFromDb).to.have.property('name', 'Item 1')
104+
expect(itemFromDb).to.not.have.property('readonly')
105+
expect(itemFromDb).to.not.have.property('requestedAt')
106+
expect(itemFromDb).to.not.have.property('promised')
107+
})
108+
})
83109
})

0 commit comments

Comments
 (0)