Skip to content

Instantly share code, notes, and snippets.

@vitaly-t
Last active November 25, 2022 05:59
Show Gist options
  • Save vitaly-t/474f15093b08caf8394afda8a5a25c7b to your computer and use it in GitHub Desktop.
Save vitaly-t/474f15093b08caf8394afda8a5a25c7b to your computer and use it in GitHub Desktop.
import {Pool} from 'pg'; // or from 'pg-pool'
import {QueryIterable, QueryIterablePool} from 'pg-iterator';
import {from, finalize, Observable} from 'rxjs';
const pool = new Pool({/* connection details */});
// RxJs helper for completing queries safely:
function fromQuery<T>(qi: QueryIterable<T>, text: string, params?: any[]): Observable<T> {
return from(qi.query(text, params)).pipe(finalize(() => qi.release()));
}
type User = {id: number, name: string};
const q = new QueryIterablePool<User>(pool); // strongly-typed pool container
fromQuery(q, 'SELECT * FROM users WHERE id < $1', [100])
.subscribe(row => {
// "row" is strongly-typed here
// "q.fields" contains all fields details from the query
// "q.stream" is the current stream (you can PAUSE/RESUME it)
console.log(row);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment