Skip to content

Commit

Permalink
feat(Brain): ensure User objects are actually User objects
Browse files Browse the repository at this point in the history
  • Loading branch information
mistydemeo committed Jan 10, 2019
1 parent f9b18be commit a6201ad
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/brain.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,28 @@ const EventEmitter = require('events').EventEmitter

const User = require('./user')

// If necessary, reconstructs a User object. Returns either:
//
// 1. If the original object was falsy, null
// 2. If the original object was a User object, the original object
// 3. If the original object was a plain JavaScript object, return
// a User object with all of the original object's properties.
let reconstructUserIfNecessary = function (user) {
if (!user) {
return null
}

if (!user.constructor || (user.constructor && user.constructor.name !== 'User')) {
let id = user.id
delete user.id
// Use the old user as the "options" object,
// populating the new user with its values.
return new User(id, user)
} else {
return user
}
}

class Brain extends EventEmitter {
// Represents somewhat persistent storage for the robot. Extend this.
//
Expand Down Expand Up @@ -116,6 +138,14 @@ class Brain extends EventEmitter {
this.data[k] = data[k]
}

// Ensure users in the brain are still User objects.
if (data && data.users) {
for (let k in data.users) {
let user = this.data.users[k]
this.data.users[k] = reconstructUserIfNecessary(user)
}
}

this.emit('loaded', this.data)
}

Expand Down
19 changes: 19 additions & 0 deletions test/brain_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,14 @@ describe('Brain', function () {
this.brain.mergeData({})
expect(this.brain.emit).to.have.been.calledWith('loaded', this.brain.data)
})

it('coerces loaded data into User objects', function () {
this.brain.mergeData({users: {'4': {'name': 'new', 'id': '4'}}})
let user = this.brain.userForId('4')
expect(user.constructor.name).to.equal('User')
expect(user.id).to.equal('4')
expect(user.name).to.equal('new')
})
})

describe('#save', () => it('emits a save event', function () {
Expand Down Expand Up @@ -308,5 +316,16 @@ describe('Brain', function () {
expect(result).to.have.members([this.user1, this.user2])
expect(result).to.not.have.members([this.user3])
})

it('returns User objects, not POJOs', function () {
expect(this.brain.userForId('1').constructor.name).to.equal('User')
for (let user of this.brain.usersForFuzzyName('Guy')) {
expect(user.constructor.name).to.equal('User')
}

for (let user of this.brain.usersForRawFuzzyName('Guy One')) {
expect(user.constructor.name).to.equal('User')
}
})
})
})

0 comments on commit a6201ad

Please sign in to comment.