11import config from 'config'
22import qs from 'query-string'
33import axios from 'axios'
4+ import { pathOr , propOr } from 'ramda'
5+
6+ let lastProcessed = null
7+ let createdConversation = false
8+
9+ function waitforTime ( milisec ) {
10+ return new Promise ( resolve => { setTimeout ( resolve , milisec ) } )
11+ }
12+
13+ const delayBetweenMessages = async ( messages , dispatch ) => {
14+ const lastMsg = messages . slice ( - 1 ) [ 0 ]
15+ const lastMessageId = propOr ( null , 'id' , lastMsg )
16+ if ( lastMessageId ) {
17+ if ( lastProcessed === lastMessageId ) {
18+ // already processed skip for now. (Bug in server return the same list over and over)
19+ return
20+ }
21+ lastProcessed = lastMessageId
22+ // For polling set the lastMessageId to avoid getting the same messages again while dispatching
23+ dispatch ( { type : 'SET_CREDENTIALS' , payload : { lastMessageId } } )
24+ }
25+ for ( const msg of messages ) {
26+ dispatch ( { type : 'ADD_MESSAGES' , payload : { messages : [ msg ] } } )
27+ if ( lastMessageId !== msg . id ) {
28+ // If there is a delay in this message wait before showing the next message.
29+ const messageDelay = pathOr ( 0 , [ 'attachment' , 'delay' ] , msg ) * 1000
30+ await waitforTime ( messageDelay )
31+ }
32+ }
33+ }
434
535export default store => next => action => {
636 if ( ! action . type . startsWith ( 'API:' ) ) {
@@ -24,7 +54,14 @@ export default store => next => action => {
2454
2555 return axios ( options )
2656 . then ( res => {
27- dispatch ( { type : `${ prefix } _SUCCESS` , payload : { ...res . data . results } } )
57+ createdConversation = createdConversation || prefix === 'CREATE_CONVERSATION'
58+ const isFirstCall = propOr ( null , 'last_message_id' , query ) === null && ! createdConversation
59+ if ( prefix === 'POLL_MESSAGES' && ! isFirstCall ) {
60+ const messages = pathOr ( [ ] , [ 'data' , 'results' , 'messages' ] , res )
61+ delayBetweenMessages ( messages , dispatch )
62+ } else {
63+ dispatch ( { type : `${ prefix } _SUCCESS` , payload : { ...res . data . results } } )
64+ }
2865 return res . data . results
2966 } )
3067 . catch ( err => {
0 commit comments