Last active
November 25, 2022 05:59
-
-
Save vitaly-t/474f15093b08caf8394afda8a5a25c7b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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