UNPKG

@dancrumb/fpish

Version:

FP-friendly classes for Typescript

89 lines (88 loc) 2.69 kB
import { Optional } from "./Optional.js"; import { RemoteDataStatus } from "./RemoteDataStatus.js"; /** * This class represents data from a remote source that takes time to load. * * This data can be a single value or an array of values. Since there's no way to * infer the shape of the data, the caller is expected to know and to make the * appropriate calls * * * @template D A type representing the shape of data that is being requested * @template E A type representing the shape of errors that can be returned */ export declare class AsyncDatum<D, E = {}> { #private; protected status: RemoteDataStatus; constructor({ status, data, error, }: { status: RemoteDataStatus; data?: D; error?: E; }); /** * Create an instance of this type that indicates that the request for async data * has not yet been made */ static notAsked<ND, NE = {}>(): AsyncDatum<ND, NE>; /** * Create an instance of this type that indicates that a request is in flight but has not * yet completed */ static loading<LD, LE = {}>(): AsyncDatum<LD, LE>; /** * Create an instance of this type that indicates that some data has been returned by the request. * * NB: There is nothing here that asserts that the request is complete. This factory method can * be called multiple times to indicate loading data in progress. * * @param data */ static loaded<LD, LE = {}>(data: LD): AsyncDatum<LD, LE>; /** * Create an instance of this type that indicates that the requests has errored. * @param error */ static errored<ED, EE = {}>(error: EE): AsyncDatum<ED, EE>; /** * * @returns true if this object currently contains retrievable data, i.e. not an error and not an inflight request */ containsData(): boolean; /** * Check the status of the data request * * @param status */ is(status: RemoteDataStatus): boolean; /** * Check whether data has been requested */ isAsked(): boolean; /** * Check whether data is currently loading */ isLoading(): boolean; /** * Check whether any data has loaded (or that the request has failed) */ isLoaded(): boolean; /** * Check whether the data errored out */ isErrored(): boolean; /** * */ value(): D; /** * Get the data as an optional and treat it as a single value */ getOptional(): Optional<D>; /** * Treats the data as an Optional and returns the internal * value or the provided value. * * @param v */ orElse(v: D): typeof v; }