Skip to content

Instantly share code, notes, and snippets.

@praslnx8
Last active March 23, 2022 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save praslnx8/df2a3802d5c84d099dcebb2bfb039b38 to your computer and use it in GitHub Desktop.
Save praslnx8/df2a3802d5c84d099dcebb2bfb039b38 to your computer and use it in GitHub Desktop.
iots
import * as t from 'io-ts/lib/index';
import { pipe } from 'fp-ts/function';
import { fold, left } from 'fp-ts/lib/Either';
import { PathReporter } from 'io-ts/lib/PathReporter';
import { Observable, throwError, of, pipe as rxjs_pipe, UnaryFunction } from 'rxjs';
import { switchMap, catchError } from 'rxjs/operators';
import { HttpError } from '../codecs/http-error';
/* istanbul ignore next */
export class DecodeError extends Error {
name = 'DecodeError';
}
/* istanbul ignore next */
export function decode<C extends t.Mixed>(codec: C): (json: unknown) => Observable<t.TypeOf<C>> {
return (json) => {
return pipe(
codec.decode(json),
fold(
(error) => throwError(new DecodeError(PathReporter.report(left(error)).join('\n'))),
(data) => of(data)
)
);
};
}
/* istanbul ignore next */
export function decodeWithHttpError<C extends t.Mixed>(
codec: C
): UnaryFunction<Observable<t.TypeOf<C>>, Observable<t.TypeOf<C>>> {
return rxjs_pipe(
switchMap(decode(codec)),
catchError((err) =>
pipe(
HttpError.decode(err),
fold(
(_error) => throwError(err),
(data) => throwError(data)
)
)
)
);
}
/* istanbul ignore next */
export const fromEnum = <T extends string, TEnumValue extends string | number>(
enumName: string,
theEnum: { [key in T]: TEnumValue }
): t.Type<TEnumValue> => {
const isEnumValue = (input: unknown): input is TEnumValue => Object.values(theEnum).includes(input);
return new t.Type<TEnumValue>(
enumName,
isEnumValue,
(input, context) => (isEnumValue(input) ? t.success(input) : t.failure(input, context)),
t.identity
);
};
import * as t from 'io-ts';
const Data = t.type({
name: t.union([t.null, t.string]),
isOnline: t.union([t.null, t.boolean])
});
type Data = t.TypeOf<typeof Data>;
export { Data };
getData(userId: string): Observable<Data> {
return this._httpRequests
.builder()
.get(`${this.getBaseUrl()}/user/${userId}`)
.pipe(decodeWithHttpError(Data));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment