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

Allow application to optionally parse messages before being displayed #29

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
35 changes: 35 additions & 0 deletions src/containers/Chat/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,44 @@ import Input from 'components/Input'
import './style.scss'

const MAX_GET_MEMORY_TIME = 10 * 1000 // in ms
const MAX_APP_PARSE_TIME = 3 * 1000 // in ms
const FAILED_TO_GET_MEMORY = 'Could not get memory from webchatMethods.getMemory :'
const FAILED_TO_PARSE = 'Application could not parse the response from backend : '
const WRONG_MEMORY_FORMAT
= 'Wrong memory format, expecting : { "memory": <json>, "merge": <boolean> }'

const getApplicationParse = messages => {
return new Promise(resolve => {
if (!window.webchatMethods || !window.webchatMethods.applicationParse) {
return resolve()
}
// so that we process the message in all cases
setTimeout(resolve, MAX_APP_PARSE_TIME)
try {
const applicationParseResponse = window.webchatMethods.applicationParse(messages)
if (!applicationParseResponse) {
return resolve()
}
if (applicationParseResponse.then && typeof applicationParseResponse.then === 'function') {
// the function returned a Promise
applicationParseResponse
.then(applicationParse => resolve())
.catch(err => {
console.error(FAILED_TO_PARSE)
console.error(err)
resolve()
})
} else {
resolve()
}
} catch (err) {
console.error(FAILED_TO_PARSE)
console.error(err)
resolve()
}
})
}

@connect(
state => ({
token: state.conversation.token,
Expand Down Expand Up @@ -61,6 +95,7 @@ class Chat extends Component {
const { messages, show } = nextProps

if (messages !== this.state.messages) {
getApplicationParse(messages)
this.setState({ messages }, () => {
const { getLastMessage } = this.props
if (getLastMessage) {
Expand Down