11import { schema } from 'normalizr'
22import _get from 'lodash/get'
33import _isFinite from 'lodash/isFinite'
4+ import addHours from 'date-fns/add_hours'
45import { defaultRoutes as api } from '../Server/Server'
56import Endpoint from '../Server/Endpoint'
67import RequestStatus from '../Server/RequestStatus'
@@ -43,13 +44,12 @@ export const fetchVirtualChallenge = function(virtualChallengeId) {
4344 api . virtualChallenge . single ,
4445 { schema : virtualChallengeSchema ( ) , variables : { id : virtualChallengeId } }
4546 ) . execute ( ) . then ( normalizedResults => {
46- // Mark that the challenge is virtual.
4747 if ( _isFinite ( normalizedResults . result ) ) {
48+ // Mark that the challenge is virtual.
4849 normalizedResults . entities . virtualChallenges [ normalizedResults . result ] . isVirtual = true
4950 }
5051
5152 dispatch ( receiveVirtualChallenges ( normalizedResults . entities ) )
52-
5353 return normalizedResults
5454 } ) . catch ( ( error ) => {
5555 dispatch ( addError ( AppErrors . virtualChallenge . fetchFailure ) )
@@ -61,11 +61,12 @@ export const fetchVirtualChallenge = function(virtualChallengeId) {
6161/**
6262 * Creates a new virtual challenge with the given name and tasks.
6363 */
64- export const createVirtualChallenge = function ( name , taskIds ) {
64+ export const createVirtualChallenge = function ( name , taskIds , expiration ) {
6565 return function ( dispatch ) {
6666 const challengeData = {
6767 name,
6868 taskIdList : taskIds ,
69+ expiry : expiration ? expiration : addHours ( new Date ( ) , 36 ) . getTime ( )
6970 }
7071
7172 return new Endpoint ( api . virtualChallenge . create , {
@@ -92,6 +93,27 @@ export const createVirtualChallenge = function(name, taskIds) {
9293}
9394
9495// redux reducers
96+ //
97+ /**
98+ * reduceVirtualChallengesFurther will be invoked by the genericEntityReducer function to
99+ * perform additional reduction on virtualChallenge entities.
100+ *
101+ * @private
102+ */
103+ const reduceVirtualChallengesFurther = function ( mergedState ,
104+ oldState ,
105+ virtualChallengeEntities ) {
106+ const now = Date . now ( )
107+ virtualChallengeEntities . forEach ( entity => {
108+ // Ignore deleted and expired virtual challenges
109+ if ( entity . deleted || entity . expired < now ) {
110+ delete mergedState [ entity . id ]
111+ return
112+ }
113+ } )
114+ }
95115
96116export const virtualChallengeEntities =
97- genericEntityReducer ( [ RECEIVE_VIRTUAL_CHALLENGES ] , 'virtualChallenges' )
117+ genericEntityReducer ( [ RECEIVE_VIRTUAL_CHALLENGES ] ,
118+ 'virtualChallenges' ,
119+ reduceVirtualChallengesFurther )
0 commit comments