Skip to content
Merged
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,16 @@ fastify.listen(3000, err => {
})
```

## TypeScript Usage

Install the compiler and typings for pg module:

```shell script
npm install --save-dev typescript @types/pg
```

You can find examples in the [examples/typescript](./examples/typescript) directory.

## Development and Testing

First, start postgres with:
Expand Down
37 changes: 37 additions & 0 deletions examples/typescript/multiple-db/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import fastify from 'fastify';

import fastifyPostgres from '../../../index';

const app = fastify();

app.register(fastifyPostgres, {
name: 'sum',
connectionString: 'postgres://user:password@host:port/sub-db',
});

app.register(fastifyPostgres, {
name: 'sub',
connectionString: 'postgres://user:password@host:port/sub-db',
});

app.get('/calc', async () => {
const sumClient = await app.pg.sum.connect();
const subClient = await app.pg.sub.connect();

const sumResult = await sumClient.query<{ sum: number }>(
'SELECT 2 + 2 as sum'
);
const subResult = await subClient.query<{ sub: number }>(
'SELECT 6 - 3 as sub'
);

sumClient.release();
subClient.release();

return {
sum: sumResult.rows,
sub: subResult.rows,
};
});

export { app };
10 changes: 10 additions & 0 deletions examples/typescript/multiple-db/fastify.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type { PostgresDb } from '../../../index';

declare module 'fastify' {
export interface FastifyInstance {
pg: {
sum: PostgresDb;
sub: PostgresDb;
};
}
}
22 changes: 22 additions & 0 deletions examples/typescript/multiple-db/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"include": ["."],
"compilerOptions": {
/* Basic Options */
"noEmit": true,
"lib": ["ES2020"],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why this version specifically?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It just example. I downgraded target settings in 4851fbd.


/* Module Resolution Options */
"esModuleInterop": true,
"resolveJsonModule": true,
"moduleResolution": "Node",

/* Strict Type-Checking Options */
"strict": true,

/* Additional Checks */
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
}
}
23 changes: 23 additions & 0 deletions examples/typescript/single-db/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import fastify from 'fastify';

import fastifyPostgres from '../../../index';

const app = fastify();

app.register(fastifyPostgres, {
connectionString: 'postgres://user:password@host:port/db',
});

app.get('/calc', async () => {
const client = await app.pg.connect();

const sumResult = await client.query<{ sum: number }>('SELECT 2 + 2 as sum');

client.release();

return {
sum: sumResult.rows,
};
});

export { app };
7 changes: 7 additions & 0 deletions examples/typescript/single-db/fastify.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type { PostgresDb } from '../../../index';

declare module 'fastify' {
export interface FastifyInstance {
pg: PostgresDb;
}
}
22 changes: 22 additions & 0 deletions examples/typescript/single-db/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"include": ["."],
"compilerOptions": {
/* Basic Options */
"noEmit": true,
"lib": ["ES2020"],

/* Module Resolution Options */
"esModuleInterop": true,
"resolveJsonModule": true,
"moduleResolution": "Node",

/* Strict Type-Checking Options */
"strict": true,

/* Additional Checks */
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
}
}
51 changes: 51 additions & 0 deletions examples/typescript/transactions/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import fastify from 'fastify';

import fastifyPostgres from '../../../index';

const app = fastify();

app.register(fastifyPostgres, {
connectionString: 'postgres://user:password@host:port/db',
});

app.post('/init-async', async () => {
const createTableQuery = `
CREATE TABLE routes (
id bigserial primary key,
name varchar(80) NOT NULL,
created_at timestamp default NULL
);
`;

return app.pg.transact(async (client) => {
const result = await client.query(createTableQuery);

return result;
});
});

app.post('/init-cb', (_req, reply) => {
const createTableQuery = `
CREATE TABLE routes (
id bigserial primary key,
name varchar(80) NOT NULL,
created_at timestamp default NULL
);
`;

app.pg.transact(
(client) => {
return client.query(createTableQuery);
},
(error, result) => {
if (error) {
reply.status(500).send(error);
return;
}

reply.status(200).send(result);
}
);
});

export { app };
7 changes: 7 additions & 0 deletions examples/typescript/transactions/fastify.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type { PostgresDb } from '../../../index';

declare module 'fastify' {
export interface FastifyInstance {
pg: PostgresDb;
}
}
22 changes: 22 additions & 0 deletions examples/typescript/transactions/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"include": ["."],
"compilerOptions": {
/* Basic Options */
"noEmit": true,
"lib": ["ES2020"],

/* Module Resolution Options */
"esModuleInterop": true,
"resolveJsonModule": true,
"moduleResolution": "Node",

/* Strict Type-Checking Options */
"strict": true,

/* Additional Checks */
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
}
}
51 changes: 51 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import type { FastifyPluginCallback } from 'fastify';
import type PgAdapter from 'pg';
import type {
Client as PgClient,
Pool as PgPool,
PoolClient as PgPoolClient,
PoolConfig as PgPoolConfig,
} from 'pg';

type CallbackArgs<TResult> =
| [error: null, result: TResult]
| [error: unknown, result: undefined];

declare function transact<TResult>(
fn: (client: PgPoolClient) => Promise<TResult>,
): Promise<TResult>;

declare function transact<TResult>(
fn: (client: PgPoolClient) => Promise<TResult>,
cb: (...args: CallbackArgs<TResult>) => void,
): void;

type PostgresDb = {
pool: PgPool;
Client: PgClient;
query: PgPool['query'];
connect: PgPool['connect'];
transact: typeof transact;
};

type Options = {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why aren't Options exported?

Copy link
Author

@evgenymarkov evgenymarkov Aug 22, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f2a868e.

/**
* Custom pg adapter
*/
pg?: typeof PgAdapter;

/**
* Use pg-native
*/
native?: boolean;

/**
* Instance name of fastify-postgres
*/
name?: string;
};

declare const PostgresPlugin: FastifyPluginCallback<Options & PgPoolConfig>;

export type { PostgresDb };
export default PostgresPlugin;
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,11 @@ function transact (fn, cb) {

function fastifyPostgres (fastify, options, next) {
let pg = defaultPg

if (options.pg) {
pg = options.pg
}

if (options.native) {
delete options.native
if (!pg.native) {
Expand Down
12 changes: 10 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
"version": "3.0.1",
"description": "Fastify PostgreSQL connection plugin",
"main": "index.js",
"types": "index.d.ts",
"scripts": {
"test": "standard && tap -J test/*.test.js",
"test": "standard && tap -J test/*.test.js && npm run test:types",
"test:types": "sh tools/build-examples.sh",
"test:report": "standard && tap -J --coverage-report=html test/*.test.js",
"test:verbose": "standard && tap -J test/*.test.js -Rspec",
"postgres": "docker run -p 5432:5432 --name fastify-postgres -e POSTGRES_PASSWORD=postgres -d postgres:11-alpine",
Expand Down Expand Up @@ -32,13 +34,19 @@
"fastify-plugin": "^2.0.0"
},
"devDependencies": {
"@types/pg": "^7.14.4",
"fastify": "^3.0.0",
"pg": "^8.2.1",
"pg-native": "^3.0.0",
"standard": "^14.0.0",
"tap": "^14.10.7"
"tap": "^14.10.7",
"typescript": "^4.0.0"
},
"peerDependencies": {
"pg": ">=6.0.0"
},
"optionalDependencies": {
"@types/pg": ">=6.0.0",
"typescript": ">=4.0.0"
}
}
7 changes: 7 additions & 0 deletions tools/build-examples.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/usr/bin/env sh

set -ex

npx tsc --project ./examples/typescript/single-db/tsconfig.json
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is not cross-platform. why not make it an npm script instead?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9e1ca07

npx tsc --project ./examples/typescript/multiple-db/tsconfig.json
npx tsc --project ./examples/typescript/transactions/tsconfig.json
14 changes: 14 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"include": ["./index.d.ts"],

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"compilerOptions": {
"noEmit": true,
"esModuleInterop": true,

"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
},
}