rxjs/operators#mergeMap JavaScript Examples

The following examples show how to use rxjs/operators#mergeMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: bookingEpic.js    From git-brunching with GNU General Public License v3.0 6 votes vote down vote up
editReservation = (action$, store) => action$.pipe(
  filter((action) => action.type === actionType.EDIT_BOOKING),
  mergeMap(async (action) => {
    const bookingData = store.value.bookingReducer;
    const restaurantData = store.value.restaurantReducer;

    const booking = await fetch(`${PUT_RESERVATION}/${bookingData.bookingCode}`, {
      method: "PUT",
      mode: "cors",
      credentials: "same-origin",
      headers: {
        Accept: "application/json, text/plain, */*",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        date: bookingData.date,
        time: bookingData.time,
        restaurantID: restaurantData.selected.ID,
        numberOfGuests: bookingData.seats,
        notes: bookingData.notes,
        name: bookingData.name,
        phone: bookingData.phone,
        email: bookingData.email,
      }),
    }).then((res) => res.json());

    return { ...action, type: actionType.EDIT_BOOKING_SUCCESS, booking };
  }),
  catchError((err) => Promise.resolve({
    type: actionType.EDIT_BOOKING_FAIL,
    message: err.message,
  })),
)
Example #2
Source File: index.js    From discovery-mobile-ui with MIT License 6 votes vote down vote up
resolveReferences = (action$, state$, { fhirClient }) => action$.pipe(
  ofType(actionTypes.RESOURCE_BATCH),
  // delay(1000), // e.g.: for debugging
  concatMap(({ payload }) => from(extractReferences(payload))
    .pipe(
      mergeMap(({
        referenceUrn, context, // referenceType, parentType,
      }) => from(fhirClient.resolve({ reference: referenceUrn, context })).pipe(
        // tap(() => console.log('Silent success referenceUrn', referenceUrn)),
        rxMap((result) => ({
          type: actionTypes.FHIR_FETCH_SUCCESS,
          payload: result,
        })),
        catchError((error) => handleError(error, `Error in resolveReferences fhirClient.resolve urn:\n ${referenceUrn}`)),
      )),
    )),
  takeUntil(action$.pipe(ofType(actionTypes.CLEAR_PATIENT_DATA))),
  repeat(),
  catchError((error) => handleError(error, 'Error in resolveReferences')),
)
Example #3
Source File: index.js    From discovery-mobile-ui with MIT License 6 votes vote down vote up
initializeFhirClient = (action$, state$, { fhirClient }) => action$.pipe(
  ofType(actionTypes.SET_AUTH),
  // delay(5000), // e.g.: for debugging -- import delay from rxjs/operators
  concatMap(({ payload }) => {
    if (payload === MOCK_AUTH) {
      return Promise.resolve({
        type: actionTypes.FHIR_FETCH_SUCCESS,
        payload: MOCK_BUNDLE,
      });
    }

    return from(fhirClient.queryPatient())
      .pipe(
        mergeMap((requestFn) => from(requestFn()).pipe(
          rxMap((result) => ({
            type: actionTypes.FHIR_FETCH_SUCCESS,
            payload: result,
          })),
          catchError((error) => handleError(error, 'Error in queryPatient', actionTypes.FHIR_FETCH_ERROR)),
        )),
      );
  }),
  takeUntil(action$.pipe(ofType(actionTypes.CLEAR_PATIENT_DATA))),
  repeat(),
  catchError((error) => handleError(error, 'Error in initializeFhirClient switchMap')),
)
Example #4
Source File: staking_payouts.js    From sdk with MIT License 6 votes vote down vote up
signAndSendExtrinsics = curry((dock, initiator, txs$) => {
  // The first nonce to be used will come from the API call
  // To send several extrinsics simultaneously, we need to emulate increasing nonce
  return from(dock.api.rpc.system.accountNextIndex(initiator.address)).pipe(
    switchMap((nonce) => {
      const sendExtrinsic = (tx) =>
        defer(() => {
          dock.setAccount(initiator);
          const sentTx = dock.signAndSend(tx, FinalizeTx, { nonce });
          // Increase nonce by hand
          nonce = nonce.add(new BN(1));

          return from(timeout(TxFinalizationTimeout, sentTx));
        }).pipe(
          mapRx((result) => ({ tx, result })),
          catchError((error, caught) => {
            console.error(` * Transaction failed: ${error}`);
            const stringified = error.toString().toLowerCase();

            // Filter out errors related to balance and double-claim
            if (
              stringified.includes("balance") ||
              stringified.includes("alreadyclaimed") ||
              stringified.includes("invalid transaction") ||
              stringified.includes("election")
            ) {
              return EMPTY;
            } else {
              // Retry an observable after the given timeout
              return timer(RetryTimeout).pipe(concatMapTo(caught));
            }
          })
        );

      return txs$.pipe(mergeMap(sendExtrinsic, ConcurrentTxLimit));
    })
  );
})
Example #5
Source File: staking_payouts.js    From sdk with MIT License 6 votes vote down vote up
getUnclaimedStashesEras = curry((api, { eras }, stashIds$) =>
  // Concurrently get unclaimed eras for each of stashes
  stashIds$.pipe(
    mergeMap(
      (stashId) =>
        from(getUnclaimedStashEras(api, eras, stashId)).pipe(
          // Filter out stashes with no unclaimed eras
          filterRx(complement(isEmpty)),
          mapRx(assoc("eras", __, { stashId }))
        ),
      ConcurrentRequestsLimit
    )
  )
)
Example #6
Source File: index.js    From sampo-ui with MIT License 6 votes vote down vote up
fetchKnowledgeGraphMetadataEpic = (action$, state$) => action$.pipe(
  ofType(FETCH_KNOWLEDGE_GRAPH_METADATA),
  withLatestFrom(state$),
  mergeMap(([action]) => {
    const requestUrl = `${apiUrl}/void/${action.perspectiveID}/${action.resultClass}`
    return ajax({
      url: requestUrl,
      method: 'GET'
    }).pipe(
      map(ajaxResponse => updateKnowledgeGraphMetadata({
        resultClass: action.resultClass,
        data: ajaxResponse.response.data ? ajaxResponse.response.data[0] : null,
        sparqlQuery: ajaxResponse.response.sparqlQuery
      })),
      catchError(error => of({
        type: FETCH_KNOWLEDGE_GRAPH_METADATA_FAILED,
        perspectiveID: action.resultClass,
        error: error,
        message: {
          text: backendErrorText,
          title: 'Error'
        }
      }))
    )
  })
)
Example #7
Source File: index.js    From sampo-ui with MIT License 6 votes vote down vote up
fetchGeoJSONLayersEpic = action$ => action$.pipe(
  ofType(FETCH_GEOJSON_LAYERS),
  mergeMap(async action => {
    const { layerIDs, bounds } = action
    try {
      const data = await Promise.all(layerIDs.map(layerID => fetchGeoJSONLayer(layerID, bounds)))
      return updateGeoJSONLayers({ payload: data })
    } catch (error) {
      return fetchGeoJSONLayersFailed({
        error,
        message: {
          text: backendErrorText,
          title: 'Error'
        }
      })
    }
  })
)
Example #8
Source File: index.js    From sampo-ui with MIT License 6 votes vote down vote up
fetchGeoJSONLayersBackendEpic = (action$, state$) => action$.pipe(
  ofType(FETCH_GEOJSON_LAYERS_BACKEND),
  withLatestFrom(state$),
  mergeMap(([action]) => {
    const { layerIDs /* bounds */ } = action
    // const { latMin, longMin, latMax, longMax } = boundsToValues(bounds)
    const params = {
      layerID: layerIDs
      // latMin,
      // longMin,
      // latMax,
      // longMax
    }
    const requestUrl = `${apiUrl}/wfs?${querystring.stringify(params)}`
    return ajax.getJSON(requestUrl).pipe(
      map(res => updateGeoJSONLayers({
        payload: res
      })),
      catchError(error => of({
        type: SHOW_ERROR,
        error: error,
        message: {
          text: backendErrorText,
          title: 'Error'
        }
      }))
    )
  })
)
Example #9
Source File: index.js    From sampo-ui with MIT License 6 votes vote down vote up
fetchSimilarDocumentsEpic = (action$, state$) => action$.pipe(
  ofType(FETCH_SIMILAR_DOCUMENTS_BY_ID),
  withLatestFrom(state$),
  mergeMap(([action]) => {
    const { resultClass, id, modelName, resultSize } = action
    const requestUrl = `${documentFinderAPIUrl}/top-similar/${modelName}/${id}?n=${resultSize}`
    return ajax.getJSON(requestUrl).pipe(
      map(res => updateInstanceTableExternal({
        resultClass,
        data: res.documents || null
      })),
      catchError(error => of({
        type: FETCH_SIMILAR_DOCUMENTS_BY_ID_FAILED,
        resultClass: action.resultClass,
        id: action.id,
        error: error,
        message: {
          text: backendErrorText,
          title: 'Error'
        }
      }))
    )
  })
)
Example #10
Source File: index.js    From sampo-ui with MIT License 6 votes vote down vote up
loadLocalesEpic = action$ => action$.pipe(
  ofType(LOAD_LOCALES),
  // https://thecodebarbarian.com/a-beginners-guide-to-redux-observable
  mergeMap(async action => {
    await intl.init({
      currentLocale: action.currentLanguage,
      locales: availableLocales,
      warningHandler: () => null
    })
    backendErrorText = intl.get('backendErrorText')
    return updateLocale({ language: action.currentLanguage })
  })
)
Example #11
Source File: index.js    From sampo-ui with MIT License 6 votes vote down vote up
fetchByURIEpic = (action$, state$) => action$.pipe(
  ofType(FETCH_BY_URI),
  withLatestFrom(state$),
  mergeMap(([action, state]) => {
    const { perspectiveID, resultClass, facetClass, uri } = action
    const params = stateToUrl({
      perspectiveID,
      facets: facetClass == null ? null : state[`${facetClass}Facets`].facets,
      facetClass
    })
    const requestUrl = `${apiUrl}/${resultClass}/page/${encodeURIComponent(uri)}`
    return ajax({
      url: requestUrl,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: params
    }).pipe(
      map(ajaxResponse => updateInstanceTable({
        resultClass,
        data: ajaxResponse.response.data,
        sparqlQuery: ajaxResponse.response.sparqlQuery
      })),
      catchError(error => of({
        type: FETCH_BY_URI_FAILED,
        resultClass: resultClass,
        error: error,
        message: {
          text: backendErrorText,
          title: 'Error'
        }
      }))
    )
  })
)
Example #12
Source File: index.js    From sampo-ui with MIT License 6 votes vote down vote up
fetchResultCountEpic = (action$, state$) => action$.pipe(
  ofType(FETCH_RESULT_COUNT),
  withLatestFrom(state$),
  mergeMap(([action, state]) => {
    const { resultClass, facetClass } = action
    const params = stateToUrl({
      facets: state[`${facetClass}Facets`].facets
    })
    const requestUrl = `${apiUrl}/faceted-search/${resultClass}/count`
    return ajax({
      url: requestUrl,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: params
    }).pipe(
      map(ajaxResponse => updateResultCount({
        resultClass,
        data: ajaxResponse.response.data,
        sparqlQuery: ajaxResponse.response.sparqlQuery
      })),
      catchError(error => of({
        type: FETCH_RESULT_COUNT_FAILED,
        resultClass,
        error: error,
        message: {
          text: backendErrorText,
          title: 'Error'
        }
      }))
    )
  })
)
Example #13
Source File: restaurantEpic.js    From git-brunching with GNU General Public License v3.0 6 votes vote down vote up
fetchSearchedRestaurants = (action$) => action$.pipe(
  filter((action) => action.type === actionType.ADD_SEARCH_RESTAURANTS),
  mergeMap(async (action) => {
    const restaurants = await fetch(`${GET_SEARCH_RESTAURANTS}${action.searchText}`).then((res) => res.json());
    return { ...action, type: actionType.ADD_RESTAURANTS_SUCCESS, restaurants };
  }),
  catchError((err) => Promise.resolve({
    type: actionType.ADD_RESTAURANTS_FAIL,
    message: err.message,
  })),
)
Example #14
Source File: restaurantEpic.js    From git-brunching with GNU General Public License v3.0 6 votes vote down vote up
fetchNewRestaurants = (action$) => action$.pipe(
  filter((action) => action.type === actionType.ADD_NEW_RESTAURANTS),
  mergeMap(async (action) => {
    const newRestaurants = await fetch(GET_NEW_RESTAURANTS).then((res) => res.json());
    return { ...action, type: actionType.ADD_NEW_RESTAURANTS_SUCCESS, newRestaurants };
  }),
  catchError((err) => Promise.resolve({
    type: actionType.ADD_RESTAURANTS_FAIL,
    message: err.message,
  })),
)
Example #15
Source File: restaurantEpic.js    From git-brunching with GNU General Public License v3.0 6 votes vote down vote up
fetchPopularRestaurants = (action$) => action$.pipe(
  filter((action) => action.type === actionType.ADD_POPULAR_RESTAURANTS),
  mergeMap(async (action) => {
    const popularRestaurants = await fetch(GET_POPULAR_RESTAURANTS).then((res) => res.json());
    return { ...action, type: actionType.ADD_POPULAR_RESTAURANTS_SUCCESS, popularRestaurants };
  }),
  catchError((err) => Promise.resolve({
    type: actionType.ADD_RESTAURANTS_FAIL,
    message: err.message,
  })),
)
Example #16
Source File: restaurantEpic.js    From git-brunching with GNU General Public License v3.0 6 votes vote down vote up
fetchOpenRestaurants = (action$) => action$.pipe(
  filter((action) => action.type === actionType.ADD_OPEN_RESTAURANTS),
  mergeMap(async (action) => {
    const openRestaurants = await fetch(GET_OPEN_RESTAURANTS).then((res) => res.json());
    return { ...action, type: actionType.ADD_OPEN_RESTAURANTS_SUCCESS, openRestaurants };
  }),
  catchError((err) => Promise.resolve({
    type: actionType.ADD_RESTAURANTS_FAIL,
    message: err.message,
  })),
)
Example #17
Source File: restaurantEpic.js    From git-brunching with GNU General Public License v3.0 6 votes vote down vote up
fetchRestaurants = (action$) => action$.pipe(
  filter((action) => action.type === actionType.ADD_RESTAURANTS),
  mergeMap(async (action) => {
    const restaurants = await fetch(GET_ALL_RESTAURANTS).then((res) => res.json());
    return { ...action, type: actionType.ADD_RESTAURANTS_SUCCESS, restaurants };
  }),
  catchError((err) => Promise.resolve({
    type: actionType.ADD_RESTAURANTS_FAIL,
    message: err.message,
  })),
)
Example #18
Source File: menu.js    From git-brunching with GNU General Public License v3.0 6 votes vote down vote up
getRestaurantMenu = (action$, store) => action$.pipe(
    filter((action) => action.type === actionType.GET_RESTAURANT_MENU),
    mergeMap(async (action) => {
      const menu = await fetch(RESTAURANT_MENU(action.restaurantID))
        .then((res) => res.json());
      return { ...action, type: actionType.GET_RESTAURANT_MENU_SUCCESS, menus: menu };
    }),
    catchError((err) => Promise.resolve({
      type: actionType.GET_RESTAURANT_MENU_FAIL,
      message: err.message,
    })),
  )
Example #19
Source File: bookingEpic.js    From git-brunching with GNU General Public License v3.0 6 votes vote down vote up
getTableCapacity = (action$, store) => action$.pipe(
  filter((action) => action.type === actionType.GET_TABLE_CAPACITY),
  mergeMap(async (action) => {
    const restaurantData = store.value.restaurantReducer;
    const capacity = await fetch(TABLE_CAPACITY(restaurantData.selected.ID)).then((res) => res.json());
    return {
      ...action,
      type: actionType.GET_TABLE_CAPACITY_SUCCESS,
      tableCapacity: capacity,
    };
  }),
  catchError((err) => Promise.resolve({
    type: actionType.GET_TABLE_CAPACITY_FAIL,
    message: err.message,
  })),
)
Example #20
Source File: bookingEpic.js    From git-brunching with GNU General Public License v3.0 6 votes vote down vote up
getAvailableHours = (action$, store) => action$.pipe(
  filter((action) => action.type === actionType.GET_AVAILABLE_RESTAURANT_HOURS),
  mergeMap(async (action) => {
    const bookingData = store.value.bookingReducer;
    const restaurantData = store.value.restaurantReducer;
    const endPoint = `${FREE_TABLE}?restaurantID=${restaurantData.selected.ID}&numberOfGuests=${bookingData.seats}&date=${bookingData.date}`;
    const available = await fetch(endPoint).then((res) => res.json());
    return {
      ...action,
      type: actionType.GET_AVAILABLE_RESTAURANT_HOURS_SUCCESS,
      availableRestaurantHours: available,
    };
  }),
  catchError((err) => Promise.resolve({
    type: actionType.GET_AVAILABLE_RESTAURANT_HOURS_FAIL,
    message: err.message,
  })),
)
Example #21
Source File: bookingEpic.js    From git-brunching with GNU General Public License v3.0 6 votes vote down vote up
getRestaurantHours = (action$, store) => action$.pipe(
  filter((action) => action.type === actionType.GET_RESTAURANT_HOURS),
  mergeMap(async (action) => {
    const restaurantData = store.value.restaurantReducer;
    const hours = await fetch(RESTAURANT_HOURS(restaurantData.selected.ID))
      .then((res) => res.json());
    return { ...action, type: actionType.GET_RESTAURANT_HOURS_SUCCESS, restaurantHours: hours };
  }),
  catchError((err) => Promise.resolve({
    type: actionType.GET_RESTAURANT_HOURS_FAIL,
    message: err.message,
  })),
)
Example #22
Source File: bookingEpic.js    From git-brunching with GNU General Public License v3.0 6 votes vote down vote up
getRestaurantBookings = (action$, store) => action$.pipe(
  filter((action) => action.type === actionType.GET_RESTAURANT_BOOKINGS),
  mergeMap(async (action) => {
    const bookingData = store.value.bookingReducer;
    const bookings = await fetch(RESTAURANT_BOOKING(bookingData.currentRestaurantID))
      .then((res) => res.json());
    return {
      ...action,
      type: actionType.GET_RESTAURANT_BOOKINGS_SUCCCESS,
      restaurantBookings: bookings.result,
    };
  }),
  catchError((err) => Promise.resolve({
    type: actionType.GET_RESTAURANT_BOOKINGS_FAIL,
    message: err.message,
  })),
)
Example #23
Source File: index.js    From sampo-ui with MIT License 5 votes vote down vote up
fetchPaginatedResultsEpic = (action$, state$) => action$.pipe(
  ofType(FETCH_PAGINATED_RESULTS),
  withLatestFrom(state$),
  mergeMap(([action, state]) => {
    const { resultClass, facetClass, sortBy } = action
    const { page, pagesize, sortDirection } = state[resultClass]
    const params = stateToUrl({
      facets: state[`${facetClass}Facets`].facets,
      facetClass: null,
      page,
      pagesize,
      sortBy,
      sortDirection
    })
    const requestUrl = `${apiUrl}/faceted-search/${resultClass}/paginated`
    // https://rxjs-dev.firebaseapp.com/api/ajax/ajax
    return ajax({
      url: requestUrl,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: params
    }).pipe(
      map(ajaxResponse =>
        updatePaginatedResults({
          resultClass,
          data: ajaxResponse.response.data,
          sparqlQuery: ajaxResponse.response.sparqlQuery
        })),
      // https://redux-observable.js.org/docs/recipes/ErrorHandling.html
      catchError(error => of({
        type: FETCH_PAGINATED_RESULTS_FAILED,
        resultClass,
        error: error,
        message: {
          text: backendErrorText,
          title: 'Error'
        }
      }))
    )
  })
)
Example #24
Source File: index.js    From sampo-ui with MIT License 5 votes vote down vote up
fetchResultsEpic = (action$, state$) => action$.pipe(
  ofType(FETCH_RESULTS),
  withLatestFrom(state$),
  mergeMap(([action, state]) => {
    const { perspectiveID, resultClass, facetClass, limit, optimize } = action
    const params = stateToUrl({
      perspectiveID,
      facets: facetClass ? state[`${facetClass}Facets`].facets : null,
      facetClass,
      uri: action.uri ? action.uri : null,
      limit,
      optimize
    })
    const requestUrl = `${apiUrl}/faceted-search/${resultClass}/all`
    // https://rxjs-dev.firebaseapp.com/api/ajax/ajax
    return ajax({
      url: requestUrl,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: params
    }).pipe(
      map(ajaxResponse => updateResults({
        resultClass,
        data: ajaxResponse.response.data,
        sparqlQuery: ajaxResponse.response.sparqlQuery,
        order: action.order
      })),
      catchError(error => of({
        type: FETCH_RESULTS_FAILED,
        resultClass,
        error: error,
        message: {
          text: backendErrorText,
          title: 'Error'
        }
      }))
    )
  })
)
Example #25
Source File: index.js    From sampo-ui with MIT License 5 votes vote down vote up
fetchInstanceAnalysisEpic = (action$, state$) => action$.pipe(
  ofType(FETCH_INSTANCE_ANALYSIS),
  withLatestFrom(state$),
  mergeMap(([action, state]) => {
    const { resultClass, facetClass, fromID, toID, period, province } = action
    const params = stateToUrl({
      facets: facetClass ? state[`${facetClass}Facets`].facets : null,
      facetClass,
      uri: action.uri ? action.uri : null,
      fromID,
      toID,
      period,
      province
    })
    const requestUrl = `${apiUrl}/faceted-search/${resultClass}/all`
    // https://rxjs-dev.firebaseapp.com/api/ajax/ajax
    return ajax({
      url: requestUrl,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: params
    }).pipe(
      map(ajaxResponse => updateInstanceAnalysisData({
        resultClass,
        data: ajaxResponse.response.data,
        sparqlQuery: ajaxResponse.response.sparqlQuery
      })),
      catchError(error => of({
        type: FETCH_RESULTS_FAILED,
        resultClass,
        error: error,
        message: {
          text: backendErrorText,
          title: 'Error'
        }
      }))
    )
  })
)
Example #26
Source File: index.js    From sampo-ui with MIT License 5 votes vote down vote up
fetchFacetEpic = (action$, state$) => action$.pipe(
  ofType(FETCH_FACET),
  withLatestFrom(state$),
  mergeMap(([action, state]) => {
    const { facetClass, facetID, constrainSelf } = action
    const facets = state[`${facetClass}Facets`].facets
    const facet = facets[facetID]
    const { sortBy = null, sortDirection = null } = facet
    const params = stateToUrl({
      facets,
      sortBy,
      sortDirection,
      constrainSelf
    })
    const requestUrl = `${apiUrl}/faceted-search/${action.facetClass}/facet/${facetID}`
    return ajax({
      url: requestUrl,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: params
    }).pipe(
      map(ajaxResponse => updateFacetValues({
        facetClass,
        id: ajaxResponse.response.id,
        data: ajaxResponse.response.data || [],
        flatData: ajaxResponse.response.flatData || [],
        sparqlQuery: ajaxResponse.response.sparqlQuery
      })),
      catchError(error => of({
        type: FETCH_FACET_FAILED,
        facetClass,
        facetID,
        error: error,
        message: {
          text: backendErrorText,
          title: 'Error'
        }
      }))
    )
  })
)
Example #27
Source File: index.js    From sampo-ui with MIT License 5 votes vote down vote up
fetchFacetConstrainSelfEpic = (action$, state$) => action$.pipe(
  ofType(FETCH_FACET_CONSTRAIN_SELF),
  withLatestFrom(state$),
  mergeMap(([action, state]) => {
    const { facetClass, facetID } = action
    const facets = state[`${facetClass}Facets`].facets
    const facet = facets[facetID]
    const { sortBy, sortDirection } = facet
    const params = stateToUrl({
      facets: facets,
      sortBy: sortBy,
      sortDirection: sortDirection,
      constrainSelf: true
    })
    const requestUrl = `${apiUrl}/faceted-search/${action.facetClass}/facet/${facetID}`
    return ajax({
      url: requestUrl,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: params
    }).pipe(
      map(ajaxResponse => updateFacetValuesConstrainSelf({
        facetClass,
        id: facetID,
        data: ajaxResponse.response.data || [],
        flatData: ajaxResponse.response.flatData || [],
        sparqlQuery: ajaxResponse.response.sparqlQuery
      })),
      catchError(error => of({
        type: FETCH_FACET_FAILED,
        resultClass: facetClass,
        id: action.id,
        error: error,
        message: {
          text: backendErrorText,
          title: 'Error'
        }
      }))
    )
  })
)
Example #28
Source File: bookingEpic.js    From git-brunching with GNU General Public License v3.0 5 votes vote down vote up
addReservation = (action$, store) => action$.pipe(
  filter((action) => action.type === actionType.ADD_BOOKING),
  mergeMap(async (action) => {
    const bookingData = store.value.bookingReducer;
    const restaurantData = store.value.restaurantReducer;

    const tableIDEndpoint = `${TABLE_ID.toString()}?date=${bookingData.date}&time=${bookingData.time.substring(0, 2)}&numberOfGuests=${bookingData.seats}&restaurantID=${restaurantData.selected.ID}`;

    const tableID = await fetch(tableIDEndpoint, {
      method: "GET",
      mode: "cors",
      credentials: "same-origin",
      headers: {
        Accept: "application/json, text/plain, */*",
        "Content-Type": "application/json",
      },
    }).then((res) => res.json());

    const booking = await fetch(POST_RESERVATION, {
      method: "POST",
      mode: "cors",
      credentials: "same-origin",
      headers: {
        Accept: "application/json, text/plain, */*",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        date: bookingData.date,
        time: bookingData.time,
        restaurantID: restaurantData.selected.ID,
        numberOfGuests: bookingData.seats,
        tableID: tableID.result[0].ID,
        notes: bookingData.notes,
        name: bookingData.name,
        phone: bookingData.phone,
        email: bookingData.email,
      }),
    }).then((res) => res.json());

    return { ...action, type: actionType.ADD_BOOKING_SUCCESS, booking };
  }),
  catchError((err) => Promise.resolve({
    type: actionType.ADD_BOOKING_FAIL,
    message: err.message,
  })),
)