diff --git a/src/brain.js b/src/brain.js index f6697dfa6..7e7b14363 100644 --- a/src/brain.js +++ b/src/brain.js @@ -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. // @@ -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) } diff --git a/test/brain_test.js b/test/brain_test.js index 99740695c..22c11f87b 100644 --- a/test/brain_test.js +++ b/test/brain_test.js @@ -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 () { @@ -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') + } + }) }) })