https://github.com/olyop/pg-helpers
pg-helpers
https://github.com/olyop/pg-helpers
Last synced: 10 months ago
JSON representation
pg-helpers
- Host: GitHub
- URL: https://github.com/olyop/pg-helpers
- Owner: olyop
- License: mit
- Created: 2021-01-24T23:11:54.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2023-02-05T03:26:33.000Z (over 3 years ago)
- Last Synced: 2025-03-29T04:41:31.198Z (about 1 year ago)
- Language: TypeScript
- Size: 131 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
- License: license
Awesome Lists containing this project
README
# pg-helpers
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
pg-helpers is a wrapper library for the popular [node-postgres](https://node-postgres.com/) library (`pg` npm package). It adds many utilities including a `query` function that makes inserting variables and parameters a lot easier in my opinion. It does this by using a simple template mechanism in your SQL code that allows you to insert a variable or a parameter.
## Installation
```sh
$ npm install @oly_op/pg-helpers
```
## Usage
`@oly_op/pg-helpers` re-exports everything from `pg`.
### types
```typescript
import type { Pool, PoolClient, QueryResult as ResultBase } from "pg";
export type PoolOrClient = Pool | PoolClient;
export type Row = Record;
export type Result = ResultBase;
```
### query helpers
#### `query`
```typescript
// definition
query(client: PoolOrClient) =>
(sql: string) =>
(input?: QueryOptions | undefined) =>
Promise;
// types
export type VariableType = string | number | boolean | null
export interface Variable {
key: string,
value: VariableType,
parameterized?: boolean,
}
export type VariableInput = Variable[] | Record
export type Parse = (result: Result) => T
export interface QueryOptionsLog {
sql?: boolean,
result?: boolean,
variables?: boolean,
}
export interface QueryOptions {
parse?: Parse,
log?: QueryOptionsLog,
variables?: VariableInput,
}
// example #1
interface User {
name: string,
userID: string,
}
const getUser =
async (userID: string) =>
query(context.pg)(`
SELECT
{{ columnNames }}
FROM
users
WHERE
user_id = '{{ userID }}'
`)({
parse: convertFirstRowToCamelCase(),
variables: {
userID,
columnNames: join(["user_id", "name"]),
},
})
console.log((await getUser("1234")).name)
```
[downloads-image]: https://img.shields.io/npm/dm/@oly_op/pg-helpers.svg
[downloads-url]: https://npmjs.org/package/@oly_op/pg-helpers
[npm-image]: https://img.shields.io/npm/v/@oly_op/pg-helpers.svg
[npm-url]: https://npmjs.org/package/@oly_op/pg-helpers