Skip to content

Commit

Permalink
Merge pull request #124 from Botfuel/brainrefactoring
Browse files Browse the repository at this point in the history
refactoring needed for the reference doc
  • Loading branch information
yangeorget authored Feb 28, 2018
2 parents bbdab82 + e6189f4 commit 19bed17
Show file tree
Hide file tree
Showing 7 changed files with 33 additions and 46 deletions.
10 changes: 5 additions & 5 deletions packages/botfuel-dialog/src/adapters/adapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ class Adapter {
*/
async handleMessage(userMessage) {
logger.debug('handleMessage', userMessage);
await this.initUserIfNecessary(userMessage.user);
await this.addUserIfNecessary(userMessage.user);
const context = {
user: userMessage.user,
brain: this.bot.brain,
Expand All @@ -104,16 +104,16 @@ class Adapter {
}

/**
* Inits the user if necessary.
* Adds the user if necessary.
* Calls the corresponding method of the brain.
* Adapters can add specific behaviour.
* @async
* @param {int} userId - the user id
* @returns {Promise.<void>}
*/
async initUserIfNecessary(userId) {
logger.debug('initUserIfNecessary', userId);
await this.bot.brain.initUserIfNecessary(userId);
async addUserIfNecessary(userId) {
logger.debug('addUserIfNecessary', userId);
await this.bot.brain.addUserIfNecessary(userId);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions packages/botfuel-dialog/src/adapters/messenger-adapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,8 @@ class MessengerAdapter extends WebAdapter {
}

/** @inheritDoc */
async initUserIfNecessary(userId) {
await super.initUserIfNecessary(userId);
async addUserIfNecessary(userId) {
await super.addUserIfNecessary(userId);
await this.updateUserProfile(userId);
}

Expand Down
32 changes: 16 additions & 16 deletions packages/botfuel-dialog/src/brains/brain.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,24 +64,13 @@ class Brain {
}

/**
* Gets the init value for creating a new conversation.
* @returns {Object}
*/
getConversationInitValue() {
return {
_dialogs: { stack: [], previous: [] },
createdAt: Date.now(),
};
}

/**
* Inits a user if necessary (if he does not exist).
* Adds a user if necessary (if he does not exist).
* @async
* @param {String} userId - the user id
* @returns {Promise.<void>}
*/
async initUserIfNecessary(userId) {
logger.debug('initUserIfNecessary', userId);
async addUserIfNecessary(userId) {
logger.debug('addUserIfNecessary', userId);
const userExists = await this.hasUser(userId);
if (!userExists) {
await this.addUser(userId);
Expand Down Expand Up @@ -119,6 +108,17 @@ class Brain {
throw new MissingImplementationError();
}

/**
* Gets the init value for creating a new conversation.
* @returns {Object}
*/
getConversationInitValue() {
return {
_dialogs: { stack: [], previous: [] },
createdAt: Date.now(),
};
}

/**
* Adds a conversation to a user.
* @async
Expand Down Expand Up @@ -231,7 +231,7 @@ class Brain {
* @param {String} key - the key
* @returns {Promise.<*>} the value
*/
async getValue() {
async botGet() {
throw new MissingImplementationError();
}

Expand All @@ -243,7 +243,7 @@ class Brain {
* @param {*} value - the value
* @returns {Promise.<*>} the new value
*/
async setValue() {
async botSet() {
throw new MissingImplementationError();
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/botfuel-dialog/src/brains/memory-brain.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,12 @@ class MemoryBrain extends Brain {
}

/** @inheritdoc */
async getValue(key) {
async botGet(key) {
return this.bot[key];
}

/** @inheritdoc */
async setValue(key, value) {
async botSet(key, value) {
this.bot[key] = value;
return value;
}
Expand Down
23 changes: 5 additions & 18 deletions packages/botfuel-dialog/src/brains/mongo-brain.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,14 @@ class MongoBrain extends Brain {
constructor(config) {
logger.debug('constructor');
super(config);
this.users = null;
}

/** @inheritdoc */
async init() {
logger.debug('init');
this.db = await MongoClient.connect(this.getMongoDbUri());
this.users = this.db.collection('users');
this.bots = this.db.collection('bots');
this.bots = this.db.collection('bots'); // TODO: is this what we need?
}

/**
Expand All @@ -49,20 +48,19 @@ class MongoBrain extends Brain {
if (process.env.MONGODB_URI) {
return process.env.MONGODB_URI;
}

if (!process.env.BOTFUEL_APP_TOKEN) {
throw new MissingCredentialsError(
'Either MONGODB_URI or BOTFUEL_APP_TOKEN is required to use the Brain with mongodb.',
);
}

return `mongodb://localhost/botfuel-bot-${process.env.BOTFUEL_APP_TOKEN}`;
}

/** @inheritdoc */
async clean() {
logger.debug('clean');
return this.users.deleteMany();
await this.bots.deleteMany();
await this.users.deleteMany();
}

/** @inheritdoc */
Expand All @@ -82,13 +80,10 @@ class MongoBrain extends Brain {
/** @inheritdoc */
async getUser(userId, ...params) {
logger.debug('getUser', userId);

const user = await this.users.findOne({ userId }, ...params);

if (!user) {
throw new Error('User does not exist');
}

return user;
}

Expand All @@ -101,11 +96,9 @@ class MongoBrain extends Brain {
*/
async findUserAndUpdate(...params) {
const user = await this.users.findOneAndUpdate(...params);

if (!user) {
throw new Error('User does not exist');
}

return user;
}

Expand All @@ -117,15 +110,13 @@ class MongoBrain extends Brain {
{ $set: { [key]: value } },
{ returnOriginal: false },
);

return result.value;
}

/** @inheritdoc */
async getLastConversation(userId) {
logger.debug('getLastConversation', userId);
const user = await this.getUser(userId, { conversations: { $slice: 1 } });

const conversation = user.conversations[0];
return this.isConversationValid(conversation) ? conversation : this.addConversation(userId);
}
Expand All @@ -138,7 +129,6 @@ class MongoBrain extends Brain {
{ $push: { conversations: { $each: [this.getConversationInitValue()], $position: 0 } } },
{ returnOriginal: false },
);

return result.value.conversations[0];
}

Expand All @@ -151,7 +141,6 @@ class MongoBrain extends Brain {
{ $set: { [`conversations.0.${key}`]: value } },
{ returnOriginal: false, sort: { 'conversations.createdAt': -1 } },
);

return result.value.conversations[0];
}

Expand All @@ -166,14 +155,13 @@ class MongoBrain extends Brain {
}

/** @inheritdoc */
async getValue(key) {
async botGet(key) {
const bot = await this.bots.findOne({});

return bot && bot[key];
}

/** @inheritdoc */
async setValue(key, value) {
async botSet(key, value) {
const bot = await this.bots.findOneAndUpdate(
{},
{
Expand All @@ -183,7 +171,6 @@ class MongoBrain extends Brain {
upsert: true,
},
);

return bot[key];
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/botfuel-dialog/tests/brains/brains.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,8 @@ const brainTest = (brainLabel) => {
});

test('should set and get value', async () => {
await brain.setValue('test', 'hello');
const value = await brain.getValue('test');
await brain.botSet('test', 'hello');
const value = await brain.botGet('test');
expect(value).toEqual('hello');
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ describe('DialogManager', () => {

beforeEach(async () => {
await brain.clean();
await brain.initUserIfNecessary(TEST_USER);
await brain.addUserIfNecessary(TEST_USER);
});

test('when given a name, it should return the correct path', () => {
Expand Down

0 comments on commit 19bed17

Please sign in to comment.