Skip to content

Instantly share code, notes, and snippets.

@dancrumb
Last active July 23, 2019 15:27
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 dancrumb/1133a8b7e4004dab9b0917c12b8a1062 to your computer and use it in GitHub Desktop.
Save dancrumb/1133a8b7e4004dab9b0917c12b8a1062 to your computer and use it in GitHub Desktop.
A TS class for representing remote data

The MIT License

Copyright (c) 2010-2019 Google, Inc. http://angularjs.org

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

export enum RemoteDataStatus {
'NotAsked',
'Loading',
'Failure',
'Success',
}
/**
* This class represents data from a remote source that takes time to load.
*/
export class RemoteData<D, E = {}> {
protected status: RemoteDataStatus = RemoteDataStatus.NotAsked;
private readonly data: ReadonlyArray<D>;
private readonly error: E;
private constructor({
status,
data,
error,
}: {
status: RemoteDataStatus;
data?: ReadonlyArray<D>;
error?: E;
}) {
this.status = status;
if (data) {
this.data = Object.freeze(data);
}
if (error) {
this.error = error;
}
}
static notAsked<D, E = {}>() {
return new RemoteData<D, E>({
status: RemoteDataStatus.NotAsked,
});
}
static loading<D, E = {}>() {
return new RemoteData<D, E>({
status: RemoteDataStatus.Loading,
});
}
static loaded<D, E = {}>(data: D[]) {
return new RemoteData<D, E>({
status: RemoteDataStatus.Success,
data: Object.freeze(data),
});
}
static errored<D, E = {}>(error: E) {
return new RemoteData<D, E>({
status: RemoteDataStatus.Failure,
error,
});
}
is(status: RemoteDataStatus) {
return this.status === status;
}
isDone() {
return (
this.status === RemoteDataStatus.Success ||
this.status === RemoteDataStatus.Failure
);
}
isEmpty() {
const value = this.value();
return value.length === 0 || (value.length === 1 && value[0] === null);
}
value(): ReadonlyArray<D> {
if (this.status === RemoteDataStatus.Success) {
return this.data;
}
throw new Error('Trying to access RemoteData before it is ready');
}
singleValue(): D {
if (this.status === RemoteDataStatus.Success) {
if (this.data.length !== 1) {
throw new Error('Data is not single-valued');
}
return this.data[0];
}
throw new Error('Trying to access RemoteData before it is ready');
}
map<U>(
callbackfn: (value: D, index: number, array?: ReadonlyArray<D>) => U,
): RemoteData<U, E> {
if (this.status === RemoteDataStatus.NotAsked) {
return RemoteData.notAsked<U, E>();
}
if (this.status === RemoteDataStatus.Loading) {
return RemoteData.loading<U, E>();
}
if (this.status === RemoteDataStatus.Failure) {
return RemoteData.errored<U, E>(this.error);
}
return RemoteData.loaded(this.data.map(callbackfn));
}
mapValue<U>(
callbackfn: (value: D, index?: number, array?: ReadonlyArray<D>) => U,
): ReadonlyArray<U> {
return this.map(callbackfn).value();
}
filter(
callbackfn: (value: D, index?: number, array?: ReadonlyArray<D>) => boolean,
): RemoteData<D, E> {
if (this.status === RemoteDataStatus.NotAsked) {
return RemoteData.notAsked<D, E>();
}
if (this.status === RemoteDataStatus.Loading) {
return RemoteData.loading<D, E>();
}
if (this.status === RemoteDataStatus.Failure) {
return RemoteData.errored<D, E>(this.error);
}
return RemoteData.loaded(this.data.filter(callbackfn));
}
reduce<U>(
callbackfn: (
previousValue: U,
currentValue: D,
currentIndex: number,
array: ReadonlyArray<D>,
) => U,
initialValue: U,
): RemoteData<U, E> {
if (this.status === RemoteDataStatus.NotAsked) {
return RemoteData.notAsked<U, E>();
}
if (this.status === RemoteDataStatus.Loading) {
return RemoteData.loading<U, E>();
}
if (this.status === RemoteDataStatus.Failure) {
return RemoteData.errored<U, E>(this.error);
}
return RemoteData.loaded<U, E>([
this.data.reduce<U>(callbackfn, initialValue),
]);
}
find(
predicate: (value: D, index: number, obj: ReadonlyArray<D>) => boolean,
// tslint:disable-next-line:no-any
thisArg?: any,
): D | undefined {
if (this.status !== RemoteDataStatus.Success) {
throw new Error('Trying to access RemoteData before it is ready');
}
return this.value().find(predicate, thisArg);
}
findIndex(
predicate: (value: D, index: number, obj: ReadonlyArray<D>) => boolean,
// tslint:disable-next-line:no-any
thisArg?: any,
) {
return this.value().findIndex(predicate, thisArg);
}
insert(index: number, value: D) {
const arr = this.value();
if (index >= arr.length) {
throw new RangeError(`Index ${index} is too large`);
} else if (index < 0) {
throw new RangeError(`Index ${index} is too small`);
}
return RemoteData.loaded(Object.assign([...arr], {[index]: value}));
}
concat(...items: (D | ConcatArray<D>)[]) {
return RemoteData.loaded(this.value().concat(...items));
}
sort(compareFn?: (a: D, b: D) => number) {
return this.value()
.slice()
.sort(compareFn);
}
}
@dancrumb
Copy link
Author

My plan:

  • Turn this into an NPM package
  • Add support for loading progress, ie to be in the Loading status, but to start populating the value so that UIs can load progressively
  • Add more list methods
  • Potentially make the code smarter about single item lists

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment