peopleware / angular-sdk

3 stars 1 forks source link

feat(async): add default service handling for facades #10

Closed glenstaes closed 7 months ago

glenstaes commented 7 months ago

Current way

Often, the default handling for a method in the facade is structured this way:

public myFacadeMethod(parameter1, parameter2): Observable<AsyncResult<ServiceResultType | null>> {
    return this.service.myServiceMethod(parameter1, parameter2).pipe(
        map((result) => createSuccessAsyncResult(result)),
        expectAsyncResultHttpError(DEFAULT_HTTP_ERROR_CODES, null)
    )
}

Proposed solution

Introduce a utility function, that allows to simplify this repetitive structure so that the code becomes smaller and it is clearer where the facade is not using this "default" way of doing things.

The end-result could be something like this:

public myFacadeMethod(parameter1, parameter2): Observable<AsyncResult<ServiceResultType | null>> {
    return defaultAsyncResultHandling(this.service.myServiceMethod(parameter1, parameter2), DEFAULT_HTTP_ERROR_CODES)
}

The same applies to the paged result syntactic sugar:

public myFacadeMethod(parameter1, parameter2): Observable<AsyncResult<ServiceResultType | null>> {
    return defaultPagedAsyncResultHandling(this.service.myServiceMethod(parameter1, parameter2), DEFAULT_HTTP_ERROR_CODES)
}

Extra logic after the default handling

Since both utility functions return an Observable, in the same way the current implementation in applications is done, it can be easily extended with extra functionality using the rxjs operators available.

public myFacadeMethod(parameter1, parameter2): Observable<AsyncResult<ServiceResultType | null>> {
    return defaultAsyncResultHandling(this.service.myServiceMethod(parameter1, parameter2), DEFAULT_HTTP_ERROR_CODES).pipe(
        tap((asyncResult) => /** e.g. dispatch the result to state management */),
        switchMap(() => this.myStateObservable$)
    )
}
glenstaes commented 7 months ago

Actual implementation turned out to be handleAsyncResult and handlePagedAsyncResult, with optional http error codes that default to DEFAULT_HTTP_ERROR_CODES:

public myFacadeMethod(parameter1, parameter2): Observable<AsyncResult<ServiceResultType | null>> {
    return handleAsyncResult(this.service.myServiceMethod(parameter1, parameter2))
}

public myFacadeMethod(parameter1, parameter2): Observable<PagedAsyncResult<ServiceResultType>> {
    return handlePagedAsyncResult(this.service.myServiceMethod(parameter1, parameter2))
}