All Projects → timdeschryver → rx-query

timdeschryver / rx-query

Licence: other
timdeschryver.github.io/rx-query/

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to rx-query

rxjs-sort-visualization
sorting algorithm visualization build by Rxjs 🐠
Stars: ✭ 16 (-91.79%)
Mutual labels:  rxjs
angular-model-pattern-example
Model pattern for Angular (2, 4, ...), manage and share your state with simple services using RxJS Subjects and Observables
Stars: ✭ 37 (-81.03%)
Mutual labels:  rxjs
py-jsonq
A simple Python package to Query over Json Data
Stars: ✭ 100 (-48.72%)
Mutual labels:  query
SQLiteHelper
🗄 This project comes in handy when you want to write a sql statement easily and smarter.
Stars: ✭ 57 (-70.77%)
Mutual labels:  query
reactive-angular-workshop
This is the source code for the world's greatest Reactive Angular Workshop.
Stars: ✭ 30 (-84.62%)
Mutual labels:  rxjs
rxrest
Reactive rest library
Stars: ✭ 33 (-83.08%)
Mutual labels:  rxjs
observer-spy
This library makes RxJS Observables testing easy!
Stars: ✭ 310 (+58.97%)
Mutual labels:  rxjs
react-rxjs
🔌 "Plug and play" for Observables in React Apps!
Stars: ✭ 36 (-81.54%)
Mutual labels:  rxjs
react-rxjs-flux
a small library for creating applications based on unidirectional data flow
Stars: ✭ 22 (-88.72%)
Mutual labels:  rxjs
kql
Kirby's Query Language API combines the flexibility of Kirby's data structures, the power of GraphQL and the simplicity of REST.
Stars: ✭ 120 (-38.46%)
Mutual labels:  query
fullstack-typescript
A demo project of a full stack typescript application
Stars: ✭ 28 (-85.64%)
Mutual labels:  rxjs
ng-observe
Angular reactivity streamlined...
Stars: ✭ 65 (-66.67%)
Mutual labels:  rxjs
powerorm
A very simple but effective php orm
Stars: ✭ 21 (-89.23%)
Mutual labels:  query
ng-effects
Reactivity system for Angular. https://ngfx.io
Stars: ✭ 46 (-76.41%)
Mutual labels:  rxjs
micro-query
Simple query string parser for Vercel's Micro
Stars: ✭ 23 (-88.21%)
Mutual labels:  query
facilejdbc
FacileJDBC - Fast, simple and lightweight JDBC wrapper
Stars: ✭ 34 (-82.56%)
Mutual labels:  query
redis-patterns-console
An interactive (and reactive) console to try and go into the deep of Redis and its patterns!
Stars: ✭ 22 (-88.72%)
Mutual labels:  rxjs
redrock
Typesafe, reactive redux
Stars: ✭ 14 (-92.82%)
Mutual labels:  rxjs
firebase-ignite
Firebase PWA Boilerplate
Stars: ✭ 12 (-93.85%)
Mutual labels:  rxjs
angular-ebook
Contains the code for the Step-by-Step Angular Guide Ebook
Stars: ✭ 28 (-85.64%)
Mutual labels:  rxjs

This package is no longer being actively maintained.

rx-query

Batteries included fetching library Fetch your data with ease and give your users a better experience

Why

Features

  • Retries
  • Cache
  • Refresh on interval, focus, online
  • Mutate data

Basics

Query without parameters

The most simple query is a parameter without parameters, it's just a wrapper around and Observable. The query method expects a callback method to invoke the query.

import { query } from "rx-query";

characters$ = query("characters", () =>
	this.rickAndMortyService.getCharacters(),
);

Query with static parameter

A query that has a static parameter (a value that doesn't change over time), can be written in the same way as a query without parameters.

import { query } from "rx-query";

characters$ = query("character", () =>
	this.rickAndMortyService.getCharacter(1),
);

An alternative way if to pass the static parameter as the first argument. The query callback will then be invoked with the passed parameter.

import { query } from "rx-query";

characters$ = query("character", 1, (characterId) =>
	this.rickAndMortyService.getCharacter(characterId),
);

Query with dynamic parameter

If a parameter can change over time (aka an Observable), it can also be passed as a parameter to query. When the input Observable emits a new value, the callback query will be invoked with the new input value.

character$ = query(
	"character",
	this.activatedRoute.params.pipe(map((p) => p.characterId)),
	(characterId: number) => this.rickAndMortyService.getCharacter(characterId),
);

Query status

A query can have the following:

  • loading: when the query is being invoked and hasn't responded yet
  • refreshing: when the query is being invoked, and there's a cached value (the cached value gets refreshed when the query is successful)
  • success: when the query returns a successful response
  • error: when the query threw an error
  • mutating: when a mutation is in progress
  • mutate-error: when a mutation threw an error

In the view layer you will often see a structure like this, with a segment to represent each status:

<ng-container *ngIf="characters$ | async as characters">
	<ng-container [ngSwitch]="characters.status">
		<div *ngSwitchCase="'loading'">Loading ... ({{ characters.retries }})</div>

		<div *ngSwitchCase="'error'">
			Something went wrong ... ({{ characters.retries }})
		</div>

		<div *ngSwitchDefault>
			<ul>
				<li *ngFor="let character of characters.data">
					<a [routerLink]="character.id">{{ character.name }}</a>
				</li>
			</ul>
		</div>
	</ng-container>
</ng-container>

Refresh a query

Use refreshQuery to trigger a new fetch from a previously contructed query.
Note that the key and parameters provided to refreshQuery should be exactly the same! The following will refetch the data and update the cache.

import { query, refreshQuery } from "rx-query";

character$ = query("character", 1, (id) =>
	this.rickAndMortyService.getCharacter(id),
);

// On some event
refreshQuery("character", 1);

Output

export type QueryOutput<QueryResult = unknown> = {
	status: Readonly<
		| "idle"
		| "success"
		| "error"
		| "loading"
		| "refreshing"
		| "mutating"
		| "mutate-error"
	>;
	data?: Readonly<QueryResult>;
	error?: Readonly<unknown>;
	retries?: Readonly<number>;
	mutate: (data: QueryResult) => void;
};

status

The current status of the query.

data

The result of the query, or the cached result.

error

The error object returned by the query. Only available in the error status.

retries

Number of query retries. Is reset every time data is fetched. Available on all statuses.

mutate

The mutate method to mutate the current query. This is optimistic, the data of the query will be modified while the request is pending. When the request resolves, the query data will be refreshed with the server data. If the request fails, the original data of the query will be restored.

Config

export type QueryConfig = {
	retries?: number | ((retryAttempt: number, error: unknown) => boolean);
	retryDelay?: number | ((retryAttempt: number) => number);
	refetchInterval?: number | Observable<unknown>;
	refetchOnWindowFocus?: boolean;
	refetchOnReconnect?: boolean;
	staleTime?: number;
	cacheTime?: number;
	mutator?: (data: QueryResult, params: QueryParam) => QueryResult;
};

retries

The number of retries to retry a query before ending up in the error status. Also accepts a callback method ((retryAttempt: number, error: unknown) => boolean) to give more control to the consumer. When a query is being retried, the status remains in the original (loading or refreshing) status. Example.

Default: 3

Usage:

{
	retries: 3,
}

{
  // Never retry when 3 attempts has been made already, or when the query is totally broken
	retries: (retryAttempt: number, error: string) =>
		retryAttempt < 3 && !error !== "Totally broken",
}

retryDelay

The delay in milliseconds before retrying the query. Also accepts a callback method ((retryAttempt: number) => number) to give more control to the consumer. Example.

Default: (n) => (n + 1) * 1000

Usage:

{
	retryDelay: 100,
}

{
  // Increase the delay with 1 second after every attempt
	retryDelay: (retryAttempt) => retryAttempt * 1000,
}

refetchInterval

Invoke the query in the background every x milliseconds, and emit the new value when the query is resolved. Example.

Default: Infinity

Usage:

{
  // every 5 minutes
	refetchInterval: 6000 * 5,
}

refetchOnWindowFocus

Invoke the query in the background when the window is focused, and emit the new value when the query is resolved. Example.

Default: true

Usage:

{
	refetchOnWindowFocus: false,
}

refetchOnReconnect

Invoke the query when the client goes back online.

Default: true

Usage:

{
	refetchOnReconnect: false,
}

cacheTime

Set the cache time (in milliseconds) for a query key. Example.

Default: 30_000 (5 minutes)

Usage:

{
	cacheTime: 60_000,
}

staleTime

Decides when a query should be refetched when it receives a trigger.

Default: 0

Usage:

{
	staleTime: 60_000,
}

mutator

The mutator, is the method that will be invoked when the mutate method is called. It receives the data passed to the mutate method and the current params of the query. Example.

Default: mutator: (data) => data

Usage:

{
  mutator: (data, queryOptions) =>
    this.http
      .post(`/persons/${queryOptions.queryParameters.id}`, data)
      // 👇 important to let the request throw in order to rollback
      .pipe(catchError((err) => throwError(err.statusText))),
}

Config override

To override the defaults for all queries, you can use the setQueryConfig method.

setQueryConfig({
	refetchOnWindowFocus: false,
	retries: 0,
	cacheTime: 60_000,
});

Inspiration

This library is inspired by:

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].