Как вернуть ошибку по умолчанию, если наблюдаемая следующая не определена - PullRequest
1 голос
/ 21 октября 2019

Я сделал сетевой запрос и получил ответ. Я хотел бы возвращать ошибку по умолчанию каждый раз, когда узнаю, что значение ответа не определено. И у меня может быть несколько уровней объектов внутри значения ответа.

Как заменить , если еще блок из кода ниже, на некоторый оператор rxjs .

import { ofType } from "redux-observable"
import { from } from "rxjs"

export const savePostEpic = (action$: any) => action$.pipe(
    ofType(Types.NewPost),
    mergeMap((action: NewPostAction) => {
        const { input } = action
        return from(somePromise(input) as Promise<MyResult>)
            .pipe(
                map(response => response.data),
                if (response.data === 'undefined') {
                    return { type: Types.Error, message: 'response is undefined' }
                } else {
                    if (response.data.createPost === 'undefined') {
                        return { type: Types.Error, message: 'response is undefined' }
                    } else {
                        return { type: Types.Post, post: reponse.data.createPost }
                    }
                }
        )
    })
)

1 Ответ

1 голос
/ 21 октября 2019

Самое близкое, что вы можете получить - https://rxjs.dev/api/operators/defaultIfEmpty ИМХО вам просто нужно провести хороший рефакторинг, и этого достаточно, чтобы уменьшить объем кода

map(response=>(response.data === 'undefined' || response.data.createPost === 'undefined')?
{ type: Types.Error, message: 'response is undefined'}:{ type: Types.Post, post: reponse.data.createPost }
)

--- defaultIfEmpty use --

pipe(
filter(response=>response.data&&response.data.createPost),
map(response=>({ type: Types.Post, post: reponse.data.createPost })),
defaultIfEmpty({ type: Types.Error, message: 'response is undefined'}),
)
...