Skip to content

Commit

Permalink
fix(core): state is loaded before all hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
Sylvain Perron committed Mar 24, 2019
1 parent 8e8c028 commit a0aefff
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 26 deletions.
2 changes: 1 addition & 1 deletion src/bp/core/botpress.ts
Expand Up @@ -214,6 +214,7 @@ export class Botpress {
await this.cmsService.initialize()

this.eventEngine.onBeforeIncomingMiddleware = async (event: sdk.IO.IncomingEvent) => {
await this.stateManager.restore(event)
await this.hookService.executeHook(new Hooks.BeforeIncomingMiddleware(this.api, event))
}

Expand All @@ -237,7 +238,6 @@ export class Botpress {
}

this.dataRetentionService.initialize()
this.stateManager.initialize()

const dialogEngineLogger = await this.loggerProvider('DialogEngine')
this.dialogEngine.onProcessingError = err => {
Expand Down
35 changes: 10 additions & 25 deletions src/bp/core/services/middleware/state-manager.ts
Expand Up @@ -27,34 +27,19 @@ export class StateManager {
private LAST_MESSAGES_HISTORY_COUNT = 5
private BOT_GLOBAL_KEY = 'global'

public initialize() {
const stateLoader = async (event: sdk.IO.Event, next: sdk.IO.MiddlewareNextCallback) => {
const incomingEvent = <sdk.IO.IncomingEvent>event
const state = incomingEvent.state
public async restore(event: sdk.IO.IncomingEvent) {
const state = event.state

const { result: user } = await this.userRepo.getOrCreate(event.channel, event.target)
state.user = user.attributes
const { result: user } = await this.userRepo.getOrCreate(event.channel, event.target)
state.user = user.attributes

const sessionId = SessionIdFactory.createIdFromEvent(event)
const session = await this.sessionRepo.get(sessionId)

state.context = (session && session.context) || {}
state.session = (session && session.session_data) || { lastMessages: [] }
state.temp = (session && session.temp_data) || {}
state.bot = await this.kvs.get(event.botId, this.BOT_GLOBAL_KEY)

next()
}

const sessionLoader: sdk.IO.MiddlewareDefinition = {
order: 0,
name: 'Session Loader',
description: 'Loads user data and session',
direction: 'incoming',
handler: stateLoader
}
const sessionId = SessionIdFactory.createIdFromEvent(event)
const session = await this.sessionRepo.get(sessionId)

this.eventEngine.register(sessionLoader)
state.context = (session && session.context) || {}
state.session = (session && session.session_data) || { lastMessages: [] }
state.temp = (session && session.temp_data) || {}
state.bot = await this.kvs.get(event.botId, this.BOT_GLOBAL_KEY)
}

public async persist(event: sdk.IO.IncomingEvent, ignoreContext: boolean) {
Expand Down

0 comments on commit a0aefff

Please sign in to comment.