Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable to access current context from within callback method #18

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/computed.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ module.exports = (Model, options) => {

// `Promise.resolve` will normalize promises and raw values
return Promise
.resolve(Model[callback](ctx.data))
.resolve(Model[callback](ctx.data, ctx.options))
.then(value => (ctx.data[property] = value))
})
})
Expand Down
25 changes: 21 additions & 4 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,23 @@ const Item = loopback.PersistedModel.extend('item', {
readonly: 'computedReadonly',
requestedAt: 'computedRequestedAt',
promised: 'computedPromised',
accessToken: 'computedAccessToken',
},
},
},
})

const testOptions = {
accessToken: {
id: 'ACCESS_TOKEN',
},
}

// Define computed property callbacks.
Item.computedReadonly = item => Boolean(item.status === 'archived')
Item.computedRequestedAt = () => now
Item.computedPromised = item => Promise.resolve(`${item.name}: As promised I get back to you!`)
Item.computedAccessToken = (item, options) => options.accessToken

// Attach model to db.
Item.attachTo(dbConnector)
Expand All @@ -63,10 +71,13 @@ describe('loopback computed property', function() {
})

before(function() {
return Promise.join(Item.findById(this.itemOne.id), Item.findById(this.itemTwo.id), (itemOne, itemTwo) => {
this.itemOne = itemOne
this.itemTwo = itemTwo
})
return Promise.join(
Item.findById(this.itemOne.id),
Item.findById(this.itemTwo.id, null, testOptions),
(itemOne, itemTwo) => {
this.itemOne = itemOne
this.itemTwo = itemTwo
})
})

it('should set the model property to the value returned by the defined callback', function() {
Expand All @@ -80,4 +91,10 @@ 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 set the model property to the value returned by the defined callback with options', function() {
/* eslint-disable no-unused-expressions */
expect(this.itemOne.accessToken).to.be.undefined
expect(this.itemTwo.accessToken.id).to.equal('ACCESS_TOKEN')
})
})