From f72f5d81b466b52db986de5581407d73bb451c3e Mon Sep 17 00:00:00 2001 From: James Sumners <321201+jsumners@users.noreply.github.com> Date: Sat, 29 Jun 2024 06:26:08 -0400 Subject: [PATCH 01/33] Merge `next` into `master` (#174) * Update for Fastify v5 (#171) * upgrade for fastify 5 * fixed typo * Update for Fastify v5 (#171) * upgrade for fastify 5 * fixed typo * update deps --------- Co-authored-by: Cristian Barlutiu --- .github/workflows/ci.yml | 2 +- package.json | 26 +++++++++++++------------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1ed9c7e..d3c718d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,7 @@ on: jobs: test: - uses: fastify/workflows/.github/workflows/plugins-ci-postgres.yml@v3 + uses: fastify/workflows/.github/workflows/plugins-ci-postgres.yml@v4.1.0 with: license-check: true lint: true diff --git a/package.json b/package.json index 08f44d5..848c34a 100644 --- a/package.json +++ b/package.json @@ -12,10 +12,10 @@ "load-data": "docker exec -it fastify-postgres psql -c 'CREATE TABLE users(id serial PRIMARY KEY, username VARCHAR (50) NOT NULL);' -U postgres -d postgres", "postgres": "docker run -p 5432:5432 --name fastify-postgres -e POSTGRES_PASSWORD=postgres -d postgres:11-alpine", "test": "npm run test:unit && npm run test:typescript", - "test:unit": "tap -J test/*.test.js", - "test:report": "standard && tap -J --coverage-report=html test/*.test.js", + "test:unit": "tap test/*.test.js", + "test:report": "standard && tap --coverage-report=html test/*.test.js", "test:typescript": "tsd", - "test:verbose": "standard && tap -J test/*.test.js -Rspec" + "test:verbose": "standard && tap test/*.test.js -Rspec" }, "repository": { "type": "git", @@ -36,18 +36,18 @@ }, "homepage": "https://github.com/fastify/fastify-postgres#readme", "dependencies": { - "fastify-plugin": "^4.0.0" + "fastify-plugin": "^5.0.0-pre.fv5.1" }, "devDependencies": { - "@tsconfig/node10": "^1.0.8", - "@types/pg": "^8.6.1", - "fastify": "^4.0.0-rc.2", - "pg": "^8.7.1", - "pg-native": "^3.0.0", - "standard": "^17.0.0", - "tap": "^16.0.0", - "tsd": "^0.31.0", - "typescript": "^5.0.2" + "@tsconfig/node10": "^1.0.9", + "@types/pg": "^8.11.4", + "fastify": "^5.0.0-alpha.3", + "pg": "^8.11.3", + "pg-native": "^3.0.1", + "standard": "^17.1.0", + "tap": "^18.7.1", + "tsd": "^0.30.7", + "typescript": "^5.4.3" }, "peerDependencies": { "pg": ">=6.0.0" From ace0759fe14252629629c8efe1ad1847842a5630 Mon Sep 17 00:00:00 2001 From: James Sumners Date: Sat, 29 Jun 2024 06:26:40 -0400 Subject: [PATCH 02/33] v6.0.0-pre.fv5.1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 848c34a..37ca06a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@fastify/postgres", - "version": "5.2.2", + "version": "6.0.0-pre.fv5.1", "description": "Fastify PostgreSQL connection plugin", "main": "index.js", "type": "commonjs", From 8b3fff9e44f77024d8bd25c2df789e05e39152b6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 1 Jul 2024 04:16:09 +0000 Subject: [PATCH 03/33] build(deps-dev): bump tsd from 0.30.7 to 0.31.1 (#175) Bumps [tsd](https://github.com/tsdjs/tsd) from 0.30.7 to 0.31.1. - [Release notes](https://github.com/tsdjs/tsd/releases) - [Commits](https://github.com/tsdjs/tsd/compare/v0.30.7...v0.31.1) --- updated-dependencies: - dependency-name: tsd dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 37ca06a..a4f0cb2 100644 --- a/package.json +++ b/package.json @@ -46,7 +46,7 @@ "pg-native": "^3.0.1", "standard": "^17.1.0", "tap": "^18.7.1", - "tsd": "^0.30.7", + "tsd": "^0.31.1", "typescript": "^5.4.3" }, "peerDependencies": { From c8f908498fe83940d4e0be7b27090e9462e2405f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 1 Jul 2024 04:44:08 +0000 Subject: [PATCH 04/33] build(deps): bump fastify/workflows from 4.1.0 to 4.2.1 (#176) Bumps [fastify/workflows](https://github.com/fastify/workflows) from 4.1.0 to 4.2.1. - [Release notes](https://github.com/fastify/workflows/releases) - [Commits](https://github.com/fastify/workflows/compare/v4.1.0...v4.2.1) --- updated-dependencies: - dependency-name: fastify/workflows dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d3c718d..1dae195 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,7 @@ on: jobs: test: - uses: fastify/workflows/.github/workflows/plugins-ci-postgres.yml@v4.1.0 + uses: fastify/workflows/.github/workflows/plugins-ci-postgres.yml@v4.2.1 with: license-check: true lint: true From 293cb13c5036667beba65a0f4677e6a1709c86e6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 1 Aug 2024 04:27:10 +0000 Subject: [PATCH 05/33] build(deps): bump fastify/workflows from 4.2.1 to 5.0.0 (#179) Bumps [fastify/workflows](https://github.com/fastify/workflows) from 4.2.1 to 5.0.0. - [Release notes](https://github.com/fastify/workflows/releases) - [Commits](https://github.com/fastify/workflows/compare/v4.2.1...v5.0.0) --- updated-dependencies: - dependency-name: fastify/workflows dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1dae195..f1e004f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,7 @@ on: jobs: test: - uses: fastify/workflows/.github/workflows/plugins-ci-postgres.yml@v4.2.1 + uses: fastify/workflows/.github/workflows/plugins-ci-postgres.yml@v5.0.0 with: license-check: true lint: true From a114e8de987390fcc15ab7c7407cb1a22895e7a1 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Tue, 6 Aug 2024 17:07:20 +0100 Subject: [PATCH 06/33] chore: update min fastify version (#178) --- index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.js b/index.js index 429fe85..168693c 100644 --- a/index.js +++ b/index.js @@ -191,7 +191,7 @@ function fastifyPostgres (fastify, options, next) { } module.exports = fp(fastifyPostgres, { - fastify: '4.x', + fastify: '5.x', name: '@fastify/postgres' }) module.exports.default = fastifyPostgres From 5cc304963a34b624cc439755d8e1cc290c756300 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Wed, 7 Aug 2024 17:28:37 +0100 Subject: [PATCH 07/33] v6.0.0-pre.fv5.2 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index a4f0cb2..8f8ee91 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@fastify/postgres", - "version": "6.0.0-pre.fv5.1", + "version": "6.0.0-pre.fv5.2", "description": "Fastify PostgreSQL connection plugin", "main": "index.js", "type": "commonjs", From ecb2f969ccce573402040b5b0c655fcdbfa4610d Mon Sep 17 00:00:00 2001 From: Matteo Collina Date: Fri, 6 Sep 2024 17:23:23 +0200 Subject: [PATCH 08/33] Bumped v6.0.0 Signed-off-by: Matteo Collina --- package.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 8f8ee91..bb2c28a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@fastify/postgres", - "version": "6.0.0-pre.fv5.2", + "version": "6.0.0", "description": "Fastify PostgreSQL connection plugin", "main": "index.js", "type": "commonjs", @@ -36,12 +36,12 @@ }, "homepage": "https://github.com/fastify/fastify-postgres#readme", "dependencies": { - "fastify-plugin": "^5.0.0-pre.fv5.1" + "fastify-plugin": "^5.0.0" }, "devDependencies": { "@tsconfig/node10": "^1.0.9", "@types/pg": "^8.11.4", - "fastify": "^5.0.0-alpha.3", + "fastify": "^5.0.0-alpha.4", "pg": "^8.11.3", "pg-native": "^3.0.1", "standard": "^17.1.0", From 058d2cc9269ede1b8547ebbaa2e5f5abeb157ccf Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Thu, 19 Sep 2024 13:42:39 +0100 Subject: [PATCH 09/33] chore: update fastify to ^5.0.0 (#180) --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index bb2c28a..121783b 100644 --- a/package.json +++ b/package.json @@ -41,7 +41,7 @@ "devDependencies": { "@tsconfig/node10": "^1.0.9", "@types/pg": "^8.11.4", - "fastify": "^5.0.0-alpha.4", + "fastify": "^5.0.0", "pg": "^8.11.3", "pg-native": "^3.0.1", "standard": "^17.1.0", From 272b0d4330b37ea181379f243887907289c89e20 Mon Sep 17 00:00:00 2001 From: Manuel Spigolon Date: Sat, 21 Sep 2024 10:56:07 +0200 Subject: [PATCH 10/33] Bumped v6.0.1 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 121783b..e37903a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@fastify/postgres", - "version": "6.0.0", + "version": "6.0.1", "description": "Fastify PostgreSQL connection plugin", "main": "index.js", "type": "commonjs", From 4d576cdf01744fb040c9debc60f4acefbbabf928 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Sat, 19 Oct 2024 09:38:23 +0100 Subject: [PATCH 11/33] build(deps-dev): lock typescript minor version (#181) --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index e37903a..9e0274b 100644 --- a/package.json +++ b/package.json @@ -47,7 +47,7 @@ "standard": "^17.1.0", "tap": "^18.7.1", "tsd": "^0.31.1", - "typescript": "^5.4.3" + "typescript": "~5.4.3" }, "peerDependencies": { "pg": ">=6.0.0" From aa3f9f1ae696d23522f6e938dbde9cde4b5506d0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 21 Oct 2024 04:30:42 +0000 Subject: [PATCH 12/33] build(deps-dev): bump typescript from 5.4.5 to 5.6.3 (#183) Bumps [typescript](https://github.com/microsoft/TypeScript) from 5.4.5 to 5.6.3. - [Release notes](https://github.com/microsoft/TypeScript/releases) - [Changelog](https://github.com/microsoft/TypeScript/blob/main/azure-pipelines.release.yml) - [Commits](https://github.com/microsoft/TypeScript/compare/v5.4.5...v5.6.3) --- updated-dependencies: - dependency-name: typescript dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 9e0274b..974833d 100644 --- a/package.json +++ b/package.json @@ -47,7 +47,7 @@ "standard": "^17.1.0", "tap": "^18.7.1", "tsd": "^0.31.1", - "typescript": "~5.4.3" + "typescript": "~5.6.3" }, "peerDependencies": { "pg": ">=6.0.0" From 753a567680f22b15b3aff26bb0ad60b2ba419b20 Mon Sep 17 00:00:00 2001 From: Dan Castillo Date: Tue, 22 Oct 2024 23:34:05 -0400 Subject: [PATCH 13/33] chore: migrate from tap to node:test and c8 using borp (#182) --- package.json | 9 +- test/add-handler.test.js | 20 +- test/initialization-log.test.js | 46 +++ test/initialization.test.js | 256 +++++------- test/query.test.js | 267 ++++++------- test/req-initialization.test.js | 147 ++++--- test/test-reporter.mjs | 68 ++++ test/transaction.test.js | 668 +++++++++++++++----------------- 8 files changed, 726 insertions(+), 755 deletions(-) create mode 100644 test/initialization-log.test.js create mode 100644 test/test-reporter.mjs diff --git a/package.json b/package.json index 974833d..8a53ca2 100644 --- a/package.json +++ b/package.json @@ -12,10 +12,9 @@ "load-data": "docker exec -it fastify-postgres psql -c 'CREATE TABLE users(id serial PRIMARY KEY, username VARCHAR (50) NOT NULL);' -U postgres -d postgres", "postgres": "docker run -p 5432:5432 --name fastify-postgres -e POSTGRES_PASSWORD=postgres -d postgres:11-alpine", "test": "npm run test:unit && npm run test:typescript", - "test:unit": "tap test/*.test.js", - "test:report": "standard && tap --coverage-report=html test/*.test.js", - "test:typescript": "tsd", - "test:verbose": "standard && tap test/*.test.js -Rspec" + "test:unit": "c8 --100 node --test", + "test:report": "standard && c8 --reporter html node --test", + "test:typescript": "tsd" }, "repository": { "type": "git", @@ -41,11 +40,11 @@ "devDependencies": { "@tsconfig/node10": "^1.0.9", "@types/pg": "^8.11.4", + "c8": "^10.1.2", "fastify": "^5.0.0", "pg": "^8.11.3", "pg-native": "^3.0.1", "standard": "^17.1.0", - "tap": "^18.7.1", "tsd": "^0.31.1", "typescript": "~5.6.3" }, diff --git a/test/add-handler.test.js b/test/add-handler.test.js index 72ab91e..3de258c 100644 --- a/test/add-handler.test.js +++ b/test/add-handler.test.js @@ -1,10 +1,10 @@ 'use strict' -const { test } = require('tap') +const { test } = require('node:test') const addHandler = require('../lib/add-handler') -test('The addHandler lib should return the right handlers structure', t => { - t.test('When the existingHandler argument is undefined', t => { +test('The addHandler lib should return the right handlers structure', async t => { + await t.test('When the existingHandler argument is undefined', t => { t.plan(1) const handlers = addHandler( @@ -12,10 +12,10 @@ test('The addHandler lib should return the right handlers structure', t => { 'test' ) - t.same(handlers, ['test']) + t.assert.deepStrictEqual(handlers, ['test']) }) - t.test('When the existingHandler argument is an array', t => { + await t.test('When the existingHandler argument is an array', t => { t.plan(1) const handlers = addHandler( @@ -23,10 +23,10 @@ test('The addHandler lib should return the right handlers structure', t => { 'again' ) - t.same(handlers, ['test', 'again']) + t.assert.deepStrictEqual(handlers, ['test', 'again']) }) - t.test('When the existingHandler argument is a function', t => { + await t.test('When the existingHandler argument is a function', t => { t.plan(2) const stub = () => 'test' @@ -36,9 +36,7 @@ test('The addHandler lib should return the right handlers structure', t => { 'again' ) - t.same(handlers[0](), 'test') - t.same(handlers[1], 'again') + t.assert.deepStrictEqual(handlers[0](), 'test') + t.assert.deepStrictEqual(handlers[1], 'again') }) - - t.end() }) diff --git a/test/initialization-log.test.js b/test/initialization-log.test.js new file mode 100644 index 0000000..a97fea0 --- /dev/null +++ b/test/initialization-log.test.js @@ -0,0 +1,46 @@ +const { test } = require('node:test') +const Fastify = require('fastify') +const pg = require('pg') +const fastifyPostgres = require('../index') +const { connectionString } = require('./helpers') + +test('Initalization log tests', async (t) => { + const realConsole = global.console + const ctx = {} + + test.beforeEach(() => { + ctx.fastify = require('fastify')() + ctx.pg = { + ...require('pg'), + native: null + } + ctx.native = pg.native + }) + + test.afterEach(() => { + // Really would just remove the module from the + // cache. + ctx.pg.native = ctx.native + global.console = realConsole + }) + + await t.test('Should print warning when native module not installed', async (t) => { + t.plan(2) + + global.console.warn = (msg) => t.assert.strictEqual(msg, "pg-native not installed, can't use native option - fallback to pg module") + + const fastify = Fastify() + t.after(() => { + fastify.close() + }) + + await ctx.fastify.register(fastifyPostgres, { + connectionString, + native: true, + pg: ctx.pg + }) + + const ready = await ctx.fastify.ready() + t.assert.ok(ready) + }) +}) diff --git a/test/initialization.test.js b/test/initialization.test.js index 0eaeec3..ff75f71 100644 --- a/test/initialization.test.js +++ b/test/initialization.test.js @@ -1,103 +1,57 @@ 'use strict' -const { test } = require('tap') +const { test } = require('node:test') const Fastify = require('fastify') -const pg = require('pg') const fastifyPostgres = require('../index') const { connectionString } = require('./helpers') -test('Should be able to use native module', (t) => { +test('Should be able to use native module', async (t) => { t.plan(2) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString, native: true }) - fastify.ready((err) => { - t.error(err) - - fastify.pg - .query('SELECT 1 AS one') - .then((result) => { - t.equal(result.rows[0].one, 1) - }) - .catch((err) => { - t.fail(err) - }) - }) -}) - -test('Should print warning when native module not installed', (t) => { - t.plan(3) - - const mockedFastifyPostgres = t.mock('../index', { - pg: { ...pg, native: null } - }) - const realConsole = global.console - global.console.warn = (msg) => t.equal(msg, "pg-native not installed, can't use native option - fallback to pg module") - - const fastify = Fastify() - t.teardown(() => { - fastify.close() - global.console = realConsole - }) + const ready = await fastify.ready() + t.assert.ok(ready) - fastify.register(mockedFastifyPostgres, { - connectionString, - native: true - }) + const result = await fastify.pg + .query('SELECT 1 AS one') - fastify.ready((err) => { - t.error(err) - - fastify.pg - .query('SELECT 1 AS one') - .then((result) => { - t.equal(result.rows[0].one, 1) - }) - .catch((err) => { - t.fail(err) - }) - }) + t.assert.strictEqual(result.rows[0].one, 1) }) -test('Should be able to use an alternative pg module', (t) => { +test('Should be able to use an alternative pg module', async (t) => { t.plan(2) const altPg = require('pg') const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString, pg: altPg }) - fastify.ready((err) => { - t.error(err) - - fastify.pg - .query('SELECT 1 AS one') - .then((result) => { - t.equal(result.rows[0].one, 1) - }) - .catch((err) => { - t.fail(err) - }) - }) + const ready = await fastify.ready() + t.assert.ok(ready) + + const result = await fastify.pg + .query('SELECT 1 AS one') + t.assert.strictEqual(result.rows[0].one, 1) }) -test('Should not throw if registered within different scopes (with and without named instances)', (t) => { +test('Should not throw if registered within different scopes (with and without named instances)', async (t) => { t.plan(1) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(function scopeOne (instance, opts, next) { + await fastify.register(function scopeOne (instance, opts, next) { instance.register(fastifyPostgres, { connectionString }) @@ -105,7 +59,7 @@ test('Should not throw if registered within different scopes (with and without n next() }) - fastify.register(function scopeTwo (instance, opts, next) { + await fastify.register(function scopeTwo (instance, opts, next) { instance.register(fastifyPostgres, { connectionString, name: 'one' @@ -119,139 +73,142 @@ test('Should not throw if registered within different scopes (with and without n next() }) - fastify.ready((err) => { - t.error(err) - }) + const ready = await fastify.ready() + t.assert.ok(ready) }) -test('Should throw when trying to register multiple instances without giving a name', (t) => { - t.plan(2) +test('Should throw when trying to register multiple instances without giving a name', async (t) => { + t.plan(3) const fastify = Fastify() - t.teardown(() => fastify.close()) - - fastify.register(fastifyPostgres, { - connectionString - }) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString }) - fastify.ready((err) => { - t.ok(err) - t.equal((err || {}).message, 'fastify-postgres has already been registered') - }) + await t.assert.rejects( + async () => await fastify.register(fastifyPostgres, { + connectionString + }), + (err) => { + t.assert.ok(err) + t.assert.strictEqual((err || {}).message, 'fastify-postgres has already been registered') + return true + } + ) }) -test('Should not throw when registering a named instance and an unnamed instance', (t) => { +test('Should not throw when registering a named instance and an unnamed instance', async (t) => { t.plan(1) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString, name: 'one' }) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString }) - fastify.ready((err) => { - t.error(err) - }) + const ready = await fastify.ready() + t.assert.ok(ready) }) -test('Should throw when trying to register duplicate connection names', (t) => { - t.plan(2) +test('Should throw when trying to register duplicate connection names', async (t) => { + t.plan(3) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) const name = 'test' - fastify + await fastify .register(fastifyPostgres, { connectionString, name }) - fastify.register(fastifyPostgres, { - connectionString, - name - }) - fastify.ready((err) => { - t.ok(err) - t.equal((err || {}).message, `fastify-postgres '${name}' instance name has already been registered`) - }) + await t.assert.rejects( + async () => await fastify.register(fastifyPostgres, { + connectionString, + name + }), + (err) => { + t.assert.ok(err) + t.assert.strictEqual((err || {}).message, `fastify-postgres '${name}' instance name has already been registered`) + return true + } + ) }) -test('Should throw when trying to register a named connection with a reserved keyword', (t) => { - t.plan(2) +test('Should throw when trying to register a named connection with a reserved keyword', async (t) => { + t.plan(3) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) const name = 'Client' - fastify.register(fastifyPostgres, { - connectionString, - name - }) - - fastify.ready((err) => { - t.ok(err) - t.equal((err || {}).message, `fastify-postgres '${name}' is a reserved keyword`) - }) + await t.assert.rejects( + async () => await fastify.register(fastifyPostgres, { + connectionString, + name + }), + (err) => { + t.assert.ok(err) + t.assert.strictEqual((err || {}).message, `fastify-postgres '${name}' is a reserved keyword`) + return true + } + ) }) -test('fastify.pg namespace should exist', (t) => { +test('const result = await fastify.pg namespace should exist', async (t) => { t.plan(5) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString }) - fastify.ready((err) => { - t.error(err) + const ready = await fastify.ready() + t.assert.ok(ready) - t.ok(fastify.pg) - t.ok(fastify.pg.connect) - t.ok(fastify.pg.pool) - t.ok(fastify.pg.Client) - }) + t.assert.ok(fastify.pg) + t.assert.ok(fastify.pg.connect) + t.assert.ok(fastify.pg.pool) + t.assert.ok(fastify.pg.Client) }) -test('fastify.pg custom namespace should exist if a name is set', (t) => { +test('const result = await fastify.pg custom namespace should exist if a name is set', async (t) => { t.plan(6) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString, name: 'test' }) - fastify.ready((err) => { - t.error(err) + const ready = await fastify.ready() + t.assert.ok(ready) - t.ok(fastify.pg) - t.ok(fastify.pg.test) - t.ok(fastify.pg.test.connect) - t.ok(fastify.pg.test.pool) - t.ok(fastify.pg.test.Client) - }) + t.assert.ok(fastify.pg) + t.assert.ok(fastify.pg.test) + t.assert.ok(fastify.pg.test.connect) + t.assert.ok(fastify.pg.test.pool) + t.assert.ok(fastify.pg.test.Client) }) -test('fastify.pg and a fastify.pg custom namespace should exist when registering a named instance before an unnamed instance)', async (t) => { - t.plan(10) +test('const result = await fastify.pg and a fastify.pg custom namespace should exist when registering a named instance before an unnamed instance)', async (t) => { + t.plan(11) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) await fastify.register(fastifyPostgres, { connectionString, @@ -262,20 +219,21 @@ test('fastify.pg and a fastify.pg custom namespace should exist when registering connectionString }) - await fastify.ready().catch(err => t.error(err)) + const ready = await fastify.ready() + t.assert.ok(ready) - t.ok(fastify.pg) - t.ok(fastify.pg.connect) - t.ok(fastify.pg.pool) - t.ok(fastify.pg.Client) + t.assert.ok(fastify.pg) + t.assert.ok(fastify.pg.connect) + t.assert.ok(fastify.pg.pool) + t.assert.ok(fastify.pg.Client) - t.ok(fastify.pg.one) - t.ok(fastify.pg.one.connect) - t.ok(fastify.pg.one.pool) - t.ok(fastify.pg.one.Client) + t.assert.ok(fastify.pg.one) + t.assert.ok(fastify.pg.one.connect) + t.assert.ok(fastify.pg.one.pool) + t.assert.ok(fastify.pg.one.Client) const result = await fastify.pg.query('SELECT NOW()') const resultOne = await fastify.pg.one.query('SELECT NOW()') - t.same(result.rowCount, 1) - t.same(resultOne.rowCount, 1) + t.assert.deepStrictEqual(result.rowCount, 1) + t.assert.deepStrictEqual(resultOne.rowCount, 1) }) diff --git a/test/query.test.js b/test/query.test.js index e963003..0d1a26e 100644 --- a/test/query.test.js +++ b/test/query.test.js @@ -1,7 +1,6 @@ 'use strict' -const t = require('tap') -const test = t.test +const { test } = require('node:test') const Fastify = require('fastify') const fastifyPostgres = require('../index') @@ -11,253 +10,215 @@ const { connectionStringBadDbName } = require('./helpers') -test('When fastify.pg root namespace is used:', (t) => { - t.test('Should be able to connect and perform a query with a callback', (t) => { +test('When fastify.pg root namespace is used:', async t => { + await t.test('Should be able to connect and perform a query with a callback', async (t) => { t.plan(4) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString }) - fastify.ready((err) => { - t.error(err) + const ready = await fastify.ready() + t.assert.ok(ready) - fastify.pg.connect(onConnect) - }) - - function onConnect (err, client, done) { - t.error(err) - - client.query('SELECT NOW()', (err, result) => { - done() - t.error(err) - t.ok(result.rows) - }) - } + const client = await fastify.pg.connect() + t.assert.ok(client) + const result = await client.query('SELECT NOW()') + t.assert.ok(result) + t.assert.ok(result.rows) + client.release() }) - t.test('Should be able to use the query util with a callback', (t) => { + await t.test('Should be able to use the query util with a callback', async (t) => { t.plan(3) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString }) - fastify.ready((err) => { - t.error(err) + const ready = await fastify.ready() + t.assert.ok(ready) - fastify.pg.query('SELECT NOW()', (err, result) => { - t.error(err) - t.ok(result.rows) - }) - }) + const result = await fastify.pg.query('SELECT NOW()') + t.assert.ok(result) + t.assert.ok(result.rows) }) - t.test('Should be able to use the query util with promises', (t) => { + await t.test('Should be able to use the query util with promises', async (t) => { t.plan(2) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString }) - fastify.ready((err) => { - t.error(err) - - fastify.pg - .query('SELECT NOW()') - .then((result) => { - t.ok(result.rows) - }) - .catch((err) => { - t.fail(err) - }) - }) + const ready = await fastify.ready() + t.assert.ok(ready) + + const result = await fastify.pg + .query('SELECT NOW()') + t.assert.ok(result.rows) }) - t.test( + await t.test( 'query util should return an error when pg fails to perform an operation using a callback', - (t) => { + async (t) => { t.plan(4) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString: connectionStringBadDbName }) - fastify.ready((err) => { - t.error(err) + const ready = await fastify.ready() + t.assert.ok(ready) - fastify.pg.query('SELECT NOW()', (err, result) => { - t.equal(result, undefined) - t.ok(err) - t.equal(err.message, `database "${BAD_DB_NAME}" does not exist`) - }) - }) + await t.assert.rejects( + async () => await fastify.pg.query('SELECT NOW()'), + (err) => { + t.assert.ok(err) + t.assert.strictEqual(err.message, `database "${BAD_DB_NAME}" does not exist`) + + return true + } + ) } ) - t.test('Should throw when pg fails to perform operation with promises', (t) => { - t.plan(3) + await t.test('Should throw when pg fails to perform operation with promises', async (t) => { + t.plan(4) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString: connectionStringBadDbName }) - fastify.ready((err) => { - t.error(err) - - fastify.pg - .query('SELECT NOW()') - .then((result) => { - t.fail(result) - }) - .catch((err) => { - t.ok(err) - t.equal(err.message, `database "${BAD_DB_NAME}" does not exist`) - }) - }) - }) + const ready = await fastify.ready() + t.assert.ok(ready) - t.end() + await t.assert.rejects( + async () => await fastify.pg + .query('SELECT NOW()'), + (err) => { + t.assert.ok(err) + t.assert.strictEqual(err.message, `database "${BAD_DB_NAME}" does not exist`) + return true + }) + }) }) -test('When fastify.pg custom namespace is used:', (t) => { - t.test('Should be able to connect and perform a query', (t) => { - t.plan(4) +test('When fastify.pg custom namespace is used:', async t => { + await t.test('Should be able to connect and perform a query', async (t) => { + t.plan(3) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString, name: 'test' }) - fastify.ready((err) => { - t.error(err) - fastify.pg.test.connect(onConnect) - }) + const ready = await fastify.ready() + t.assert.ok(ready) + const client = await fastify.pg.test.connect() - function onConnect (err, client, done) { - t.error(err) - client.query('SELECT NOW()', (err, result) => { - done() - t.error(err) - t.ok(result.rows) - }) - } + const result = await client.query('SELECT NOW()') + t.assert.ok(ready) + t.assert.ok(result.rows) + + client.release() }) - t.test('Should be able to use query util with a callback', (t) => { - t.plan(3) + await t.test('Should be able to use query util with a callback', async (t) => { + t.plan(2) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString, name: 'test' }) - fastify.ready((err) => { - t.error(err) - fastify.pg.test.query('SELECT NOW()', (err, result) => { - t.error(err) - t.ok(result.rows) - }) - }) + const ready = await fastify.ready() + t.assert.ok(ready) + const result = await fastify.pg.test.query('SELECT NOW()') + t.assert.ok(result.rows) }) - t.test('Should be able to use query util with promises', (t) => { + await t.test('Should be able to use query util with promises', async (t) => { t.plan(2) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString, name: 'test' }) - fastify.ready((err) => { - t.error(err) - - fastify.pg.test - .query('SELECT NOW()') - .then((result) => { - t.ok(result.rows) - }) - .catch((err) => { - t.fail(err) - }) - }) + const ready = await fastify.ready() + t.assert.ok(ready) + + const result = await fastify.pg.test + .query('SELECT NOW()') + t.assert.ok(result.rows) }) - t.test('Should be able to use native module', (t) => { + await t.test('Should be able to use native module', async (t) => { t.plan(2) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString, name: 'test', native: true }) - fastify.ready((err) => { - t.error(err) - - fastify.pg.test - .query('SELECT 1 AS one') - .then((result) => { - t.equal(result.rows[0].one, 1) - }) - .catch((err) => { - t.fail(err) - }) - }) + const ready = await fastify.ready() + t.assert.ok(ready) + + const result = await fastify.pg.test + .query('SELECT 1 AS one') + t.assert.strictEqual(result.rows[0].one, 1) }) - t.test('Should throw when pg fails to perform an operation with promises', (t) => { - t.plan(3) + await t.test('Should throw when pg fails to perform an operation with promises', async (t) => { + t.plan(4) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString: connectionStringBadDbName, name: 'test' }) - fastify.ready((err) => { - t.error(err) - - fastify.pg.test - .query('SELECT NOW()') - .then((result) => { - t.fail(result) - }) - .catch((err) => { - t.ok(err) - t.equal(err.message, `database "${BAD_DB_NAME}" does not exist`) - }) - }) - }) + const ready = await fastify.ready() + t.assert.ok(ready) - t.end() + await t.assert.rejects( + async () => await fastify.pg.test + .query('SELECT NOW()'), + (err) => { + t.assert.ok(err) + t.assert.strictEqual(err.message, `database "${BAD_DB_NAME}" does not exist`) + return true + }) + }) }) diff --git a/test/req-initialization.test.js b/test/req-initialization.test.js index acacc14..485b815 100644 --- a/test/req-initialization.test.js +++ b/test/req-initialization.test.js @@ -1,16 +1,16 @@ 'use strict' -const { test } = require('tap') +const { test } = require('node:test') const Fastify = require('fastify') const fastifyPostgres = require('../index') const { connectionString } = require('./helpers') const extractUserCount = response => parseInt(JSON.parse(response.payload).rows[0].userCount) -test('When we use the fastify-postgres transaction route option', t => { - t.test('Should be able to execute queries provided to the request pg decorator', async t => { +test('When we use the fastify-postgres transaction route option', async t => { + await t.test('Should be able to execute queries provided to the request pg decorator', async t => { const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) await fastify.register(fastifyPostgres, { connectionString @@ -37,12 +37,12 @@ test('When we use the fastify-postgres transaction route option', t => { url: '/count-users' }) - t.equal(extractUserCount(response), 2) + t.assert.strictEqual(extractUserCount(response), 2) }) - t.test('Should be able to execute queries provided to a namespaced request pg decorator', async t => { + await t.test('Should be able to execute queries provided to a namespaced request pg decorator', async t => { const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) await fastify.register(fastifyPostgres, { connectionString, @@ -71,12 +71,12 @@ test('When we use the fastify-postgres transaction route option', t => { url: '/count-users' }) - t.equal(extractUserCount(response), 2) + t.assert.strictEqual(extractUserCount(response), 2) }) - t.test('Should trigger a rollback when failing to execute a query provided to the request pg decorator', async t => { + await t.test('Should trigger a rollback when failing to execute a query provided to the request pg decorator', async t => { const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) await fastify.register(fastifyPostgres, { connectionString @@ -105,12 +105,12 @@ test('When we use the fastify-postgres transaction route option', t => { url: '/count-users' }) - t.equal(extractUserCount(response), 0) + t.assert.strictEqual(extractUserCount(response), 0) }) - t.test('Should trigger a rollback when failing to execute a query provided to a namespaced request pg decorator', async t => { + await t.test('Should trigger a rollback when failing to execute a query provided to a namespaced request pg decorator', async t => { const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) await fastify.register(fastifyPostgres, { connectionString, @@ -140,12 +140,12 @@ test('When we use the fastify-postgres transaction route option', t => { url: '/count-users' }) - t.equal(extractUserCount(response), 0) + t.assert.strictEqual(extractUserCount(response), 0) }) - t.test('Should work properly with `schema` option and validation failure', async t => { + await t.test('Should work properly with `schema` option and validation failure', async t => { const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) await fastify.register(fastifyPostgres, { connectionString @@ -163,7 +163,7 @@ test('When we use the fastify-postgres transaction route option', t => { }, pg: { transact: true } }, async (req, reply) => { - t.fail('should never execute the handler') + t.assert.fail('should never execute the handler') }) const response = await fastify.inject({ @@ -171,108 +171,99 @@ test('When we use the fastify-postgres transaction route option', t => { method: 'POST', body: { notValid: 'json input' } }) - t.not(response.body, 'never success') - t.equal(response.json().code, 'FST_ERR_VALIDATION') + t.assert.notStrictEqual(response.body, 'never success') + t.assert.strictEqual(response.json().code, 'FST_ERR_VALIDATION') }) - - t.end() }) -test('Should not add hooks with combinations of registration `options.name` and route options `pg.transact`', t => { - t.test('Should not add hooks when `transact` is not set', t => { +test('Should not add hooks with combinations of registration `options.name` and route options `pg.transact`', async t => { + await t.test('Should not add hooks when `transact` is not set', async t => { t.plan(1) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString - }).after(() => { - fastify.get('/', (req, reply) => { - t.equal(req.pg, null) - }) }) - fastify.inject({ url: '/' }) + fastify.get('/', async (req, reply) => { + t.assert.strictEqual(req.pg, null) + }) + await fastify.inject({ url: '/' }) }) - t.test('Should not add hooks when `name` is set and `transact` is not set', t => { + await t.test('Should not add hooks when `name` is set and `transact` is not set', async t => { t.plan(1) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString, name: 'test' - }).after(() => { - fastify.get('/', (req, reply) => { - t.equal(req.pg, null) - }) + }) + fastify.get('/', async (req, reply) => { + t.assert.strictEqual(req.pg, null) }) - fastify.inject({ url: '/' }) + await fastify.inject({ url: '/' }) }) - t.test('Should not add hooks when `name` is set and `transact` is set to `true`', t => { + await t.test('Should not add hooks when `name` is set and `transact` is set to `true`', async t => { t.plan(1) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString, name: 'test' - }).after(() => { - fastify.get('/', { pg: { transact: true } }, (req, reply) => { - t.equal(req.pg, null) - }) + }) + fastify.get('/', { pg: { transact: true } }, async (req, reply) => { + t.assert.strictEqual(req.pg, null) }) - fastify.inject({ url: '/' }) + await fastify.inject({ url: '/' }) }) - t.test('Should not add hooks when `name` is not set and `transact` is set and is a string', t => { + await t.test('Should not add hooks when `name` is not set and `transact` is set and is a string', async t => { t.plan(1) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString - }).after(() => { - fastify.get('/', { pg: { transact: 'test' } }, (req, reply) => { - t.equal(req.pg, null) - }) + }) + fastify.get('/', { pg: { transact: 'test' } }, async (req, reply) => { + t.assert.strictEqual(req.pg, null) }) - fastify.inject({ url: '/' }) + await fastify.inject({ url: '/' }) }) - t.test('Should not add hooks when `name` and `transact` are set to different strings', t => { + await t.test('Should not add hooks when `name` and `transact` are set to different strings', async t => { t.plan(1) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString, name: 'test' - }).after(() => { - fastify.get('/', { pg: { transact: 'different' } }, (req, reply) => { - t.equal(req.pg, null) - }) + }) + fastify.get('/', { pg: { transact: 'different' } }, async (req, reply) => { + t.assert.strictEqual(req.pg, null) }) - fastify.inject({ url: '/' }) + await fastify.inject({ url: '/' }) }) - - t.end() }) -test('Should throw errors with incorrect combinations of registration `options.name` and route options `pg.transact`', t => { - t.test('Should throw an error when `name` is set as reserved keyword', async t => { +test('Should throw errors with incorrect combinations of registration `options.name` and route options `pg.transact`', async t => { + await t.test('Should throw an error when `name` is set as reserved keyword', async t => { const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) const name = 'user' @@ -281,19 +272,19 @@ test('Should throw errors with incorrect combinations of registration `options.n name }) - fastify.get('/', { pg: { transact: name } }, (req, reply) => {}) + fastify.get('/', { pg: { transact: name } }, async (req, reply) => {}) const response = await fastify.inject({ url: '/' }) - t.same(response.json(), { + t.assert.deepStrictEqual(response.json(), { statusCode: 500, error: 'Internal Server Error', message: `request client '${name}' does not exist` }) }) - t.test('Should throw an error when pg client has already been registered with the same name', async t => { + await t.test('Should throw an error when pg client has already been registered with the same name', async t => { const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) const name = 'test' @@ -304,19 +295,19 @@ test('Should throw errors with incorrect combinations of registration `options.n fastify.addHook('onRequest', async (req, reply) => { req.pg = { [name]: await fastify.pg[name].connect() } }) - fastify.get('/', { pg: { transact: name } }, (req, reply) => {}) + fastify.get('/', { pg: { transact: name } }, async (req, reply) => {}) const response = await fastify.inject({ url: '/' }) - t.same(response.json(), { + t.assert.deepStrictEqual(response.json(), { statusCode: 500, error: 'Internal Server Error', message: `request client '${name}' has already been registered` }) }) - t.test('Should throw an error when pg client has already been registered', async t => { + await t.test('Should throw an error when pg client has already been registered', async t => { const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) await fastify.register(fastifyPostgres, { connectionString @@ -324,15 +315,13 @@ test('Should throw errors with incorrect combinations of registration `options.n fastify.addHook('onRequest', async (req, reply) => { req.pg = await fastify.pg.connect() }) - fastify.get('/', { pg: { transact: true } }, (req, reply) => {}) + fastify.get('/', { pg: { transact: true } }, async (req, reply) => {}) const response = await fastify.inject({ url: '/' }) - t.same(response.json(), { + t.assert.deepStrictEqual(response.json(), { statusCode: 500, error: 'Internal Server Error', message: 'request client has already been registered' }) }) - - t.end() }) diff --git a/test/test-reporter.mjs b/test/test-reporter.mjs new file mode 100644 index 0000000..bf7087e --- /dev/null +++ b/test/test-reporter.mjs @@ -0,0 +1,68 @@ +function colorize (type, text) { + if (type === 'pass') { + const blackText = `\x1b[30m${text}` + const boldblackText = `\x1b[1m${blackText}` + // Green background with black text + return `\x1b[42m${boldblackText}\x1b[0m` + } + + if (type === 'fail') { + const whiteText = `\x1b[37m${text}` + const boldWhiteText = `\x1b[1m${whiteText}` + // Red background with white text + return `\x1b[41m${boldWhiteText}\x1b[0m` + } + + return text +} + +function formatDiagnosticStr (str) { + return str.replace(/^(\w+)(\s*\d*)/i, (_, firstWord, rest) => { + return firstWord.charAt(0).toUpperCase() + firstWord.slice(1).toLowerCase() + ':' + rest + }) +} + +async function * reporter (source) { + const failed = new Set() + const diagnostics = new Set() + + for await (const event of source) { + switch (event.type) { + case 'test:pass': { + yield `${colorize('pass', 'PASSED')}: ${event.data.file || event.data.name}\n` + break + } + + case 'test:fail': { + failed.add(event.data.name || event.data.file) + yield `${colorize('fail', 'FAILED')}: ${event.data.file || event.data.name}\n` + break + } + + case 'test:diagnostic': { + diagnostics.add(`${formatDiagnosticStr(event.data.message)}\n`) + break + } + + default: { + yield '' + } + } + } + + if (failed.size > 0) { + yield `\n\n${colorize('fail', 'Failed tests:')}\n` + for (const file of failed) { + yield `${file}\n` + } + } + + yield '\n' + + for (const diagnostic of diagnostics) { + yield `${diagnostic}` + } + yield '\n' +} + +export default reporter diff --git a/test/transaction.test.js b/test/transaction.test.js index de636d6..49ef630 100644 --- a/test/transaction.test.js +++ b/test/transaction.test.js @@ -1,7 +1,6 @@ 'use strict' -const t = require('tap') -const test = t.test +const { test } = require('node:test') const Fastify = require('fastify') const pg = require('pg') const fastifyPostgres = require('../index') @@ -11,243 +10,208 @@ const { connectionStringBadDbName } = require('./helpers') -test('When fastify.pg root namespace is used:', (t) => { - t.test('Should be able to use transact util with a callback', (t) => { - t.plan(4) +test('When fastify.pg root namespace is used:', async (t) => { + await t.test('Should be able to use transact util with a callback', async (t) => { + t.plan(3) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { connectionString }) + await fastify.register(fastifyPostgres, { connectionString }) - fastify.ready((err) => { - t.error(err) + const ready = await fastify.ready() + t.assert.ok(ready) - fastify.pg.transact( - (client) => - client.query('INSERT INTO users(username) VALUES($1) RETURNING id', [ - 'root-with-callback' - ]), - function (err, result) { - t.error(err) - t.equal(result.rows.length, 1) + const result = await fastify.pg.transact( + (client) => + client.query('INSERT INTO users(username) VALUES($1) RETURNING id', [ + 'root-with-callback' + ]) + ) + t.assert.strictEqual(result.rows.length, 1) - const userId = result.rows[0].id + const userId = result.rows[0].id - fastify.pg - .query('SELECT * FROM users WHERE id = $1', [userId]) - .then((result) => { - t.equal(result.rows[0].username, 'root-with-callback') - }) - .catch((err) => { - t.fail(err) - }) - } - ) - }) + const result2 = await fastify.pg + .query('SELECT * FROM users WHERE id = $1', [userId]) + t.assert.strictEqual(result2.rows[0].username, 'root-with-callback') }) - t.test('Should be able to use transact util with promises', (t) => { + await t.test('Should be able to use transact util with promises', async (t) => { t.plan(3) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { connectionString }) + await fastify.register(fastifyPostgres, { connectionString }) - fastify.ready((err) => { - t.error(err) + const ready = await fastify.ready() + t.assert.ok(ready) - fastify.pg - .transact((client) => - client.query('INSERT INTO users(username) VALUES($1) RETURNING id', ['root-with-promise']) - ) - .then((result) => { - t.equal(result.rows.length, 1) + const result = await fastify.pg + .transact((client) => + client.query('INSERT INTO users(username) VALUES($1) RETURNING id', ['root-with-promise']) + ) + t.assert.strictEqual(result.rows.length, 1) - const userId = result.rows[0].id + const userId = result.rows[0].id - fastify.pg - .query('SELECT * FROM users WHERE id = $1', [userId]) - .then((result) => { - t.equal(result.rows[0].username, 'root-with-promise') - }) - .catch((err) => { - t.fail(err) - }) - }) - .catch((err) => { - t.fail(err) - }) - }) + const result2 = await fastify.pg + .query('SELECT * FROM users WHERE id = $1', [userId]) + t.assert.strictEqual(result2.rows[0].username, 'root-with-promise') }) - t.test('Should be able to use transact util with a commit callback', (t) => { + await t.test('Should be able to use transact util with a commit callback', async (t) => { t.plan(4) const fastify = Fastify() - t.teardown(() => fastify.close()) - - fastify.register(fastifyPostgres, { connectionString }) - - fastify.ready((err) => { - t.error(err) - - fastify.pg.transact( - (client, commit) => - client.query( - 'INSERT INTO users(username) VALUES($1) RETURNING id', - ['root-commit-callback'], - (err, id) => { - commit(err, id) - } - ), - function (err, result) { - t.error(err) - t.equal(result.rows.length, 1) - - const userId = result.rows[0].id - - fastify.pg - .query('SELECT * FROM users WHERE id = $1', [userId]) - .then((result) => { - t.equal(result.rows[0].username, 'root-commit-callback') - }) - .catch((err) => { - t.fail(err) - }) - } - ) - }) + t.after(() => fastify.close()) + + await fastify.register(fastifyPostgres, { connectionString }) + + const ready = await fastify.ready() + t.assert.ok(ready) + + const result = await fastify.pg.transact( + (client, commit) => + client.query( + 'INSERT INTO users(username) VALUES($1) RETURNING id', + ['root-commit-callback'], + (err, id) => { + commit(err, id) + } + )) + t.assert.ok(ready) + t.assert.strictEqual(result.rows.length, 1) + + const userId = result.rows[0].id + + const result2 = await fastify.pg + .query('SELECT * FROM users WHERE id = $1', [userId]) + t.assert.strictEqual(result2.rows[0].username, 'root-commit-callback') }) - t.test('Should trigger a rollback when something goes wrong (with callback)', (t) => { + await t.test('Should trigger a rollback when something goes wrong (with callback)', async (t) => { t.plan(9) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { connectionString }) + await fastify.register(fastifyPostgres, { connectionString }) - fastify.ready((err) => { - t.error(err) + const ready = await fastify.ready() + t.assert.ok(ready) - fastify.pg.transact( - (client) => { - return client + await t.assert.rejects( + async () => await fastify.pg.transact( + async (client) => { + const result = await client .query('INSERT INTO users(username) VALUES($1) RETURNING id', [ 'root-rollback-user-callback' ]) - .then((result) => { - t.ok(result) + t.assert.ok(result) - const userId = result.rows[0].id + const userId = result.rows[0].id - return client - .query('SELECT * FROM users WHERE id = $1', [userId]) - .then((result) => { - t.ok(result) - t.equal(result.rows[0].username, 'root-rollback-user-callback') - }) - .then(() => { - throw new Error('We make it throw on purpose to trigger a rollback') - }) - }) - }, - function (err, result) { - t.ok(err) - t.equal(err.message, 'We make it throw on purpose to trigger a rollback') - t.equal(result, undefined) - - fastify.pg - .query('SELECT * FROM users WHERE username = \'root-rollback-user-callback\'') - .then((result) => { - t.ok(result) - t.equal(result.rows.length, 0) - }) - .catch((err) => { - t.fail(err) - }) - } - ) - }) + const result2 = await client + .query('SELECT * FROM users WHERE id = $1', [userId]) + t.assert.ok(result2) + t.assert.strictEqual(result2.rows[0].username, 'root-rollback-user-callback') + throw new Error('We make it throw on purpose to trigger a rollback') + }), + (err) => { + t.assert.ok(err) + t.assert.strictEqual(err.message, 'We make it throw on purpose to trigger a rollback') + return true + } + ) + + const result3 = await fastify.pg + .query('SELECT * FROM users WHERE username = \'root-rollback-user-callback\'') + t.assert.ok(result3) + t.assert.strictEqual(result3.rows.length, 0) }) - t.test('Should trigger a rollback when something goes wrong (with promises)', (t) => { + await t.test('Should trigger a rollback when something goes wrong (with promises)', async (t) => { t.plan(8) - const fastify = Fastify() - t.teardown(() => fastify.close()) - - fastify.register(fastifyPostgres, { connectionString }) - - fastify.ready((err) => { - t.error(err) - - fastify.pg - .transact((client) => - client - .query('INSERT INTO users(username) VALUES($1) RETURNING id', [ - 'root-rollback-user-promise' - ]) - .then((result) => { - t.ok(result) - - const userId = result.rows[0].id - - return client - .query('SELECT * FROM users WHERE id = $1', [userId]) - .then((result) => { - t.ok(result) - t.equal(result.rows[0].username, 'root-rollback-user-promise') - }) - .then(() => { - throw new Error('We make it throw on purpose to trigger a rollback') - }) - }) - ) - .catch((err) => { - t.ok(err) - t.equal(err.message, 'We make it throw on purpose to trigger a rollback') - - fastify.pg - .query('SELECT * FROM users WHERE username = \'root-rollback-user-promise\'') - .then((result) => { - t.ok(result) - t.equal(result.rows.length, 0) - }) - .catch((err) => { - t.fail(err) - }) - }) + await new Promise((resolve) => { + const fastify = Fastify() + t.after(() => fastify.close()) + + fastify.register(fastifyPostgres, { connectionString }) + + fastify.ready((err) => { + t.assert.ifError(err) + + fastify.pg + .transact((client) => + client + .query('INSERT INTO users(username) VALUES($1) RETURNING id', [ + 'root-rollback-user-promise' + ]) + .then((result) => { + t.assert.ok(result) + + const userId = result.rows[0].id + + return client + .query('SELECT * FROM users WHERE id = $1', [userId]) + .then((result) => { + t.assert.ok(result) + t.assert.strictEqual(result.rows[0].username, 'root-rollback-user-promise') + }) + .then(() => { + throw new Error('We make it throw on purpose to trigger a rollback') + }) + }) + ) + .catch((err) => { + t.assert.ok(err) + t.assert.strictEqual(err.message, 'We make it throw on purpose to trigger a rollback') + + fastify.pg + .query('SELECT * FROM users WHERE username = \'root-rollback-user-promise\'') + .then((result) => { + t.assert.ok(result) + t.assert.strictEqual(result.rows.length, 0) + resolve() + }) + .catch((err) => { + t.assert.ifError(err) + }) + }) + }) }) }) - t.test('Should throw if the pool connection throws an error', (t) => { - t.plan(3) + await t.test('Should throw if the pool connection throws an error', async (t) => { + t.plan(4) const fastify = Fastify() - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString: connectionStringBadDbName }) - fastify.ready((err) => { - t.error(err) + const ready = await fastify.ready() + t.assert.ok(ready) - fastify.pg.transact((client) => client.query('SELECT NOW()')) - .catch((err) => { - t.ok(err) - t.equal(err.message, `database "${BAD_DB_NAME}" does not exist`) - }) - }) + await t.assert.rejects( + async () => await fastify.pg.transact((client) => client.query('SELECT NOW()')), + (err) => { + t.assert.ok(err) + t.assert.strictEqual(err.message, `database "${BAD_DB_NAME}" does not exist`) + return true + } + ) }) - t.test('Should trigger a rollback when it is impossible to begin transaction', (t) => { + await t.test('Should trigger a rollback when it is impossible to begin transaction', async (t) => { t.plan(4) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) class FakeClient extends pg.Client { query (cmd, cb) { @@ -269,27 +233,26 @@ test('When fastify.pg root namespace is used:', (t) => { } } - fastify.register(fastifyPostgres, { connectionString, pg: { ...pg, Pool: FakePool } }) + await fastify.register(fastifyPostgres, { connectionString, pg: { ...pg, Pool: FakePool } }) - fastify.ready((err) => { - t.error(err) + const ready = await fastify.ready() + t.assert.ok(ready) - fastify.pg.transact( - (client) => {}, - function (err, result) { - t.ok(err) - t.equal(err.message, 'Boom') - t.equal(result, undefined) - } - ) - }) + await t.assert.rejects( + async () => await fastify.pg.transact((client) => {}), + (err) => { + t.assert.ok(err) + t.assert.strictEqual(err.message, 'Boom') + return true + } + ) }) - t.test('Should trigger a rollback when it is impossible to commit transaction', (t) => { - t.plan(3) + await t.test('Should trigger a rollback when it is impossible to commit transaction', async (t) => { + t.plan(4) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) class FakeClient extends pg.Client { query (queryText, values, cb) { @@ -314,12 +277,13 @@ test('When fastify.pg root namespace is used:', (t) => { } } - fastify.register(fastifyPostgres, { connectionString, pg: { ...pg, Pool: FakePool } }) + await fastify.register(fastifyPostgres, { connectionString, pg: { ...pg, Pool: FakePool } }) - fastify.ready((err) => { - t.error(err) + const ready = await fastify.ready() + t.assert.ok(ready) - fastify.pg.transact( + await t.assert.rejects( + async () => await fastify.pg.transact( (client, commit) => { return client.query('INSERT INTO users(username) VALUES($1) RETURNING id', [ 'root-rollback-commit' @@ -327,225 +291,213 @@ test('When fastify.pg root namespace is used:', (t) => { commit(err, res) }) } - ).then((result) => { - t.equal(result, undefined) - }).catch(err => { - t.ok(err) - t.equal(err.message, 'Boom') + ), + (err) => { + t.assert.ok(err) + t.assert.strictEqual(err.message, 'Boom') + return true }) - }) }) - - t.end() }) -test('When fastify.pg.test namespace is used:', (t) => { - t.test('Should be able to use transact util with a callback', (t) => { +test('When fastify.pg.test namespace is used:', async (t) => { + await t.test('Should be able to use transact util with a callback', async (t) => { t.plan(4) - const fastify = Fastify() - t.teardown(() => fastify.close()) - - fastify.register(fastifyPostgres, { - connectionString, - name: 'test' - }) + await new Promise((resolve) => { + const fastify = Fastify() + t.after(() => fastify.close()) - fastify.ready((err) => { - t.error(err) - - fastify.pg.test.transact( - (client) => - client.query('INSERT INTO users(username) VALUES($1) RETURNING id', [ - 'namespace-with-callback' - ]), - function (err, result) { - t.error(err) - t.equal(result.rows.length, 1) - - const userId = result.rows[0].id + fastify.register(fastifyPostgres, { + connectionString, + name: 'test' + }) - fastify.pg.test - .query('SELECT * FROM users WHERE id = $1', [userId]) - .then((result) => { - t.equal(result.rows[0].username, 'namespace-with-callback') - }) - .catch((err) => { - t.fail(err) - }) - } - ) + fastify.ready((err) => { + t.assert.ifError(err) + + fastify.pg.test.transact( + (client) => + client.query('INSERT INTO users(username) VALUES($1) RETURNING id', [ + 'namespace-with-callback' + ]), + function (err, result) { + t.assert.ifError(err) + t.assert.strictEqual(result.rows.length, 1) + + const userId = result.rows[0].id + + fastify.pg.test + .query('SELECT * FROM users WHERE id = $1', [userId]) + .then((result) => { + t.assert.strictEqual(result.rows[0].username, 'namespace-with-callback') + resolve() + }) + .catch((err) => { + t.fail(err) + }) + } + ) + }) }) }) - t.test('Should be able to use transact util with promises', (t) => { + await t.test('Should be able to use transact util with promises', async (t) => { t.plan(3) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString, name: 'test' }) - fastify.ready((err) => { - t.error(err) + const ready = await fastify.ready() + t.assert.ok(ready) - fastify.pg.test - .transact((client) => - client.query('INSERT INTO users(username) VALUES($1) RETURNING id', [ - 'namespace-with-promise' - ]) - ) - .then((result) => { - t.equal(result.rows.length, 1) + const result = await fastify.pg.test + .transact((client) => + client.query('INSERT INTO users(username) VALUES($1) RETURNING id', [ + 'namespace-with-promise' + ]) + ) + t.assert.strictEqual(result.rows.length, 1) - const userId = result.rows[0].id + const userId = result.rows[0].id - fastify.pg.test - .query('SELECT * FROM users WHERE id = $1', [userId]) - .then((result) => { - t.equal(result.rows[0].username, 'namespace-with-promise') - }) - .catch((err) => { - t.fail(err) - }) - }) - .catch((err) => { - t.fail(err) - }) - }) + const result2 = await fastify.pg.test + .query('SELECT * FROM users WHERE id = $1', [userId]) + t.assert.strictEqual(result2.rows[0].username, 'namespace-with-promise') }) - t.test('Should trigger a rollback when something goes wrong (with callback)', (t) => { + await t.test('Should trigger a rollback when something goes wrong (with callback)', async (t) => { t.plan(9) - const fastify = Fastify() - t.teardown(() => fastify.close()) + await new Promise((resolve) => { + const fastify = Fastify() + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { - connectionString, - name: 'test' - }) - - fastify.ready((err) => { - t.error(err) - - fastify.pg.test.transact( - (client) => { - return client - .query('INSERT INTO users(username) VALUES($1) RETURNING id', [ - 'namespace-rollback-user-callback' - ]) - .then((result) => { - t.ok(result) - - const userId = result.rows[0].id + fastify.register(fastifyPostgres, { + connectionString, + name: 'test' + }) - return client - .query('SELECT * FROM users WHERE id = $1', [userId]) - .then((result) => { - t.ok(result) - t.equal(result.rows[0].username, 'namespace-rollback-user-callback') - }) - .then(() => { - throw new Error('We make it throw on purpose to trigger a rollback') - }) - }) - }, - function (err, result) { - t.ok(err) - t.equal(err.message, 'We make it throw on purpose to trigger a rollback') - t.equal(result, undefined) - - fastify.pg.test - .query('SELECT * FROM users WHERE username = \'namespace-rollback-user-callback\'') - .then((result) => { - t.ok(result) - t.equal(result.rows.length, 0) - }) - .catch((err) => { - t.fail(err) - }) - } - ) + fastify.ready((err) => { + t.assert.ifError(err) + + fastify.pg.test.transact( + (client) => { + return client + .query('INSERT INTO users(username) VALUES($1) RETURNING id', [ + 'namespace-rollback-user-callback' + ]) + .then((result) => { + t.assert.ok(result) + + const userId = result.rows[0].id + + return client + .query('SELECT * FROM users WHERE id = $1', [userId]) + .then((result) => { + t.assert.ok(result) + t.assert.strictEqual(result.rows[0].username, 'namespace-rollback-user-callback') + }) + .then(() => { + throw new Error('We make it throw on purpose to trigger a rollback') + }) + }) + }, + function (err, result) { + t.assert.ok(err) + t.assert.strictEqual(err.message, 'We make it throw on purpose to trigger a rollback') + t.assert.strictEqual(result, undefined) + + fastify.pg.test + .query('SELECT * FROM users WHERE username = \'namespace-rollback-user-callback\'') + .then((result) => { + t.assert.ok(result) + t.assert.strictEqual(result.rows.length, 0) + resolve() + }) + .catch((err) => { + t.fail(err) + }) + } + ) + }) }) }) - t.test('Should trigger a rollback when something goes wrong (with promises)', (t) => { - t.plan(8) + await t.test('Should trigger a rollback when something goes wrong (with promises)', async (t) => { + t.plan(9) const fastify = Fastify() - t.teardown(() => fastify.close()) + t.after(() => fastify.close()) - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString, name: 'test' }) - fastify.ready((err) => { - t.error(err) + const ready = await fastify.ready() + t.assert.ok(ready) - fastify.pg.test - .transact((client) => + await t.assert.rejects( + async () => await fastify.pg.test + .transact(async (client) => client .query('INSERT INTO users(username) VALUES($1) RETURNING id', [ 'namespace-rollback-user-promise' ]) .then((result) => { - t.ok(result) + t.assert.ok(result) const userId = result.rows[0].id return client .query('SELECT * FROM users WHERE id = $1', [userId]) .then((result) => { - t.ok(result) - t.equal(result.rows[0].username, 'namespace-rollback-user-promise') + t.assert.ok(result) + t.assert.strictEqual(result.rows[0].username, 'namespace-rollback-user-promise') }) .then(() => { throw new Error('We make it throw on purpose to trigger a rollback') }) }) - ) - .catch((err) => { - t.ok(err) - t.equal(err.message, 'We make it throw on purpose to trigger a rollback') + ), + (err) => { + t.assert.ok(err) + t.assert.strictEqual(err.message, 'We make it throw on purpose to trigger a rollback') + return true + }) - fastify.pg.test - .query('SELECT * FROM users WHERE username = \'namespace-rollback-user-promise\'') - .then((result) => { - t.ok(result) - t.equal(result.rows.length, 0) - }) - .catch((err) => { - t.fail(err) - }) - }) - }) + const result = await fastify.pg.test + .query('SELECT * FROM users WHERE username = \'namespace-rollback-user-promise\'') + t.assert.ok(result) + t.assert.strictEqual(result.rows.length, 0) }) - t.test('Should throw if the pool connection throws an error', (t) => { - t.plan(3) + await t.test('Should throw if the pool connection throws an error', async (t) => { + t.plan(4) const fastify = Fastify() - fastify.register(fastifyPostgres, { + await fastify.register(fastifyPostgres, { connectionString: connectionStringBadDbName, name: 'test' }) - fastify.ready((err) => { - t.error(err) + const ready = await fastify.ready() + t.assert.ok(ready) - fastify.pg.test.transact((client) => client.query('SELECT NOW()')) - .catch((err) => { - t.ok(err) - t.equal(err.message, `database "${BAD_DB_NAME}" does not exist`) - }) - }) + await t.assert.rejects( + async () => await fastify.pg.test.transact((client) => client.query('SELECT NOW()')), + (err) => { + t.assert.ok(err) + t.assert.strictEqual(err.message, `database "${BAD_DB_NAME}" does not exist`) + return true + } + ) }) - - t.end() }) From e1aed07d00c21f142f71dcdccbbf4a59c4fb99a8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 1 Nov 2024 04:20:02 +0000 Subject: [PATCH 14/33] build(deps): bump fastify/workflows from 5.0.0 to 5.0.1 (#184) Bumps [fastify/workflows](https://github.com/fastify/workflows) from 5.0.0 to 5.0.1. - [Release notes](https://github.com/fastify/workflows/releases) - [Commits](https://github.com/fastify/workflows/compare/v5.0.0...v5.0.1) --- updated-dependencies: - dependency-name: fastify/workflows dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f1e004f..ad739a5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,7 @@ on: jobs: test: - uses: fastify/workflows/.github/workflows/plugins-ci-postgres.yml@v5.0.0 + uses: fastify/workflows/.github/workflows/plugins-ci-postgres.yml@v5.0.1 with: license-check: true lint: true From 9ec7a0a124822d47a517029c16127d7cb8f4c961 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Fri, 1 Nov 2024 10:38:18 +0000 Subject: [PATCH 15/33] ci: use major version of workflows --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ad739a5..9d9f3b3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,7 @@ on: jobs: test: - uses: fastify/workflows/.github/workflows/plugins-ci-postgres.yml@v5.0.1 + uses: fastify/workflows/.github/workflows/plugins-ci-postgres.yml@v5 with: license-check: true lint: true From 06ad44ae6a869f2ad7e40a444dd44f4d7e4c39e1 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Sun, 3 Nov 2024 12:34:48 +0000 Subject: [PATCH 16/33] style: remove trailing whitespace (#185) --- index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/index.d.ts b/index.d.ts index 8efa159..e8bf52a 100644 --- a/index.d.ts +++ b/index.d.ts @@ -50,12 +50,12 @@ declare namespace fastifyPostgres { export function transact( fn: (client: Pg.PoolClient) => Promise ): Promise; - + export function transact( fn: (client: Pg.PoolClient) => Promise, cb: (error: Error | null, result?: TResult) => void ): void; - + export const fastifyPostgres: FastifyPostgres export { fastifyPostgres as default } } From eb517e7ded9634e0bd68888b508df1f0b3e9f8fc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 25 Nov 2024 04:07:33 +0000 Subject: [PATCH 17/33] build(deps-dev): bump typescript from 5.6.3 to 5.7.2 (#186) Bumps [typescript](https://github.com/microsoft/TypeScript) from 5.6.3 to 5.7.2. - [Release notes](https://github.com/microsoft/TypeScript/releases) - [Changelog](https://github.com/microsoft/TypeScript/blob/main/azure-pipelines.release.yml) - [Commits](https://github.com/microsoft/TypeScript/compare/v5.6.3...v5.7.2) --- updated-dependencies: - dependency-name: typescript dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 8a53ca2..905d6c1 100644 --- a/package.json +++ b/package.json @@ -46,7 +46,7 @@ "pg-native": "^3.0.1", "standard": "^17.1.0", "tsd": "^0.31.1", - "typescript": "~5.6.3" + "typescript": "~5.7.2" }, "peerDependencies": { "pg": ">=6.0.0" From b5336bdb722cc99bb9ef9d286426629863421389 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Thu, 5 Dec 2024 14:17:58 +0000 Subject: [PATCH 18/33] docs(readme): update ci badge syntax (#187) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index acd70b1..de6079e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # @fastify/postgres -![CI](https://github.com/fastify/fastify-postgres/workflows/CI/badge.svg) +[![CI](https://github.com/fastify/fastify-postgres/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/fastify/fastify-postgres/actions/workflows/ci.yml) [![NPM version](https://img.shields.io/npm/v/@fastify/postgres.svg?style=flat)](https://www.npmjs.com/package/@fastify/postgres) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/) From 5b8600844e47cb8a7a0caef66cf0a4dc70e26f81 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Sun, 29 Dec 2024 19:22:35 +0000 Subject: [PATCH 19/33] chore(package): add funding and contribs (#189) --- package.json | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/package.json b/package.json index 905d6c1..5d0df4d 100644 --- a/package.json +++ b/package.json @@ -29,11 +29,40 @@ "sql" ], "author": "Tomas Della Vedova - @delvedor (http://delved.org)", + "contributors": [ + { + "name": "Matteo Collina", + "email": "hello@matteocollina.com" + }, + { + "name": "Manuel Spigolon", + "email": "behemoth89@gmail.com" + }, + { + "name": "Aras Abbasi", + "email": "aras.abbasi@gmail.com" + }, + { + "name": "Frazer Smith", + "email": "frazer.dev@icloud.com", + "url": "https://github.com/fdawgs" + } + ], "license": "MIT", "bugs": { "url": "https://github.com/fastify/fastify-postgres/issues" }, "homepage": "https://github.com/fastify/fastify-postgres#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], "dependencies": { "fastify-plugin": "^5.0.0" }, From 5bb4c9c51a95b5ce6d6d2e3e3dc7cb5d9e6a9beb Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Mon, 6 Jan 2025 16:51:30 +0000 Subject: [PATCH 20/33] perf(index): use optional chaining (#191) Signed-off-by: Frazer Smith --- index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.js b/index.js index 168693c..3a44415 100644 --- a/index.js +++ b/index.js @@ -125,7 +125,7 @@ function fastifyPostgres (fastify, options, next) { } fastify.addHook('onRoute', routeOptions => { - const transact = routeOptions && routeOptions.pg && routeOptions.pg.transact + const transact = routeOptions?.pg?.transact if ( !transact || From 59178eededfe5414767dd16fa0b10346d9e71658 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Mon, 6 Jan 2025 16:51:42 +0000 Subject: [PATCH 21/33] refactor: prefix unused params with underscores (#190) --- index.js | 6 +++--- test/initialization.test.js | 4 ++-- test/req-initialization.test.js | 34 ++++++++++++++++----------------- test/transaction.test.js | 2 +- 4 files changed, 23 insertions(+), 23 deletions(-) diff --git a/index.js b/index.js index 3a44415..7c0577d 100644 --- a/index.js +++ b/index.js @@ -96,7 +96,7 @@ function fastifyPostgres (fastify, options, next) { transact: transact.bind(pool) } - fastify.addHook('onClose', (fastify, done) => pool.end(done)) + fastify.addHook('onClose', (_fastify, done) => pool.end(done)) if (name) { if (db[name]) { @@ -135,7 +135,7 @@ function fastifyPostgres (fastify, options, next) { return } - const preHandler = async (req, reply) => { + const preHandler = async (req) => { const client = await pool.connect() if (name) { @@ -164,7 +164,7 @@ function fastifyPostgres (fastify, options, next) { await client.query('BEGIN') } - const onError = (req, reply, error, done) => { + const onError = (req, _reply, _error, done) => { req[transactionFailedSymbol] = true extractRequestClient(req, transact).query('ROLLBACK', done) } diff --git a/test/initialization.test.js b/test/initialization.test.js index ff75f71..ebaf2d6 100644 --- a/test/initialization.test.js +++ b/test/initialization.test.js @@ -51,7 +51,7 @@ test('Should not throw if registered within different scopes (with and without n const fastify = Fastify() t.after(() => fastify.close()) - await fastify.register(function scopeOne (instance, opts, next) { + await fastify.register(function scopeOne (instance, _opts, next) { instance.register(fastifyPostgres, { connectionString }) @@ -59,7 +59,7 @@ test('Should not throw if registered within different scopes (with and without n next() }) - await fastify.register(function scopeTwo (instance, opts, next) { + await fastify.register(function scopeTwo (instance, _opts, next) { instance.register(fastifyPostgres, { connectionString, name: 'one' diff --git a/test/req-initialization.test.js b/test/req-initialization.test.js index 485b815..6f71d40 100644 --- a/test/req-initialization.test.js +++ b/test/req-initialization.test.js @@ -18,13 +18,13 @@ test('When we use the fastify-postgres transaction route option', async t => { await fastify.pg.query('DELETE FROM "users" WHERE TRUE') - fastify.get('/count-users', async (req, reply) => { + fastify.get('/count-users', async () => { const result = await fastify.pg.query('SELECT COUNT(*) AS "userCount" FROM users WHERE username=\'pass-opt-in\'') return result }) - fastify.get('/pass', { pg: { transact: true } }, async (req, reply) => { + fastify.get('/pass', { pg: { transact: true } }, async (req) => { await req.pg.query('INSERT INTO users(username) VALUES($1) RETURNING id', ['pass-opt-in']) await req.pg.query('INSERT INTO users(username) VALUES($1) RETURNING id', ['pass-opt-in']) return 'complete' @@ -51,13 +51,13 @@ test('When we use the fastify-postgres transaction route option', async t => { await fastify.pg.test.query('DELETE FROM "users" WHERE TRUE') - fastify.get('/count-users', async (req, reply) => { + fastify.get('/count-users', async () => { const result = await fastify.pg.test.query('SELECT COUNT(*) AS "userCount" FROM users WHERE username=\'pass-opt-in\'') return result }) - fastify.get('/pass', { pg: { transact: 'test' } }, async (req, reply) => { + fastify.get('/pass', { pg: { transact: 'test' } }, async (req) => { await req.pg.test.query('INSERT INTO users(username) VALUES($1) RETURNING id', ['pass-opt-in']) await req.pg.test.query('INSERT INTO users(username) VALUES($1) RETURNING id', ['pass-opt-in']) @@ -84,7 +84,7 @@ test('When we use the fastify-postgres transaction route option', async t => { await fastify.pg.query('DELETE FROM "users" WHERE TRUE') - fastify.get('/count-users', async (req, reply) => { + fastify.get('/count-users', async (_req, reply) => { const result = await fastify.pg.query('SELECT COUNT(*) AS "userCount" FROM users WHERE username=\'fail-opt-in\'') reply.send(result) @@ -119,7 +119,7 @@ test('When we use the fastify-postgres transaction route option', async t => { await fastify.pg.test.query('DELETE FROM "users" WHERE TRUE') - fastify.get('/count-users', async (req, reply) => { + fastify.get('/count-users', async (_req, reply) => { const result = await fastify.pg.test.query('SELECT COUNT(*) AS "userCount" FROM users WHERE username=\'fail-opt-in\'') reply.send(result) @@ -162,7 +162,7 @@ test('When we use the fastify-postgres transaction route option', async t => { } }, pg: { transact: true } - }, async (req, reply) => { + }, async () => { t.assert.fail('should never execute the handler') }) @@ -186,7 +186,7 @@ test('Should not add hooks with combinations of registration `options.name` and await fastify.register(fastifyPostgres, { connectionString }) - fastify.get('/', async (req, reply) => { + fastify.get('/', async (req) => { t.assert.strictEqual(req.pg, null) }) await fastify.inject({ url: '/' }) @@ -202,7 +202,7 @@ test('Should not add hooks with combinations of registration `options.name` and connectionString, name: 'test' }) - fastify.get('/', async (req, reply) => { + fastify.get('/', async (req) => { t.assert.strictEqual(req.pg, null) }) @@ -219,7 +219,7 @@ test('Should not add hooks with combinations of registration `options.name` and connectionString, name: 'test' }) - fastify.get('/', { pg: { transact: true } }, async (req, reply) => { + fastify.get('/', { pg: { transact: true } }, async (req) => { t.assert.strictEqual(req.pg, null) }) @@ -235,7 +235,7 @@ test('Should not add hooks with combinations of registration `options.name` and await fastify.register(fastifyPostgres, { connectionString }) - fastify.get('/', { pg: { transact: 'test' } }, async (req, reply) => { + fastify.get('/', { pg: { transact: 'test' } }, async (req) => { t.assert.strictEqual(req.pg, null) }) @@ -252,7 +252,7 @@ test('Should not add hooks with combinations of registration `options.name` and connectionString, name: 'test' }) - fastify.get('/', { pg: { transact: 'different' } }, async (req, reply) => { + fastify.get('/', { pg: { transact: 'different' } }, async (req) => { t.assert.strictEqual(req.pg, null) }) @@ -272,7 +272,7 @@ test('Should throw errors with incorrect combinations of registration `options.n name }) - fastify.get('/', { pg: { transact: name } }, async (req, reply) => {}) + fastify.get('/', { pg: { transact: name } }, async () => {}) const response = await fastify.inject({ url: '/' }) t.assert.deepStrictEqual(response.json(), { @@ -292,10 +292,10 @@ test('Should throw errors with incorrect combinations of registration `options.n connectionString, name }) - fastify.addHook('onRequest', async (req, reply) => { + fastify.addHook('onRequest', async (req) => { req.pg = { [name]: await fastify.pg[name].connect() } }) - fastify.get('/', { pg: { transact: name } }, async (req, reply) => {}) + fastify.get('/', { pg: { transact: name } }, async () => {}) const response = await fastify.inject({ url: '/' }) t.assert.deepStrictEqual(response.json(), { @@ -312,10 +312,10 @@ test('Should throw errors with incorrect combinations of registration `options.n await fastify.register(fastifyPostgres, { connectionString }) - fastify.addHook('onRequest', async (req, reply) => { + fastify.addHook('onRequest', async (req) => { req.pg = await fastify.pg.connect() }) - fastify.get('/', { pg: { transact: true } }, async (req, reply) => {}) + fastify.get('/', { pg: { transact: true } }, async () => {}) const response = await fastify.inject({ url: '/' }) t.assert.deepStrictEqual(response.json(), { diff --git a/test/transaction.test.js b/test/transaction.test.js index 49ef630..8453f05 100644 --- a/test/transaction.test.js +++ b/test/transaction.test.js @@ -239,7 +239,7 @@ test('When fastify.pg root namespace is used:', async (t) => { t.assert.ok(ready) await t.assert.rejects( - async () => await fastify.pg.transact((client) => {}), + async () => await fastify.pg.transact(() => {}), (err) => { t.assert.ok(err) t.assert.strictEqual(err.message, 'Boom') From cea66ead73528c8a2c90fae50aa235de5dedfcc6 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Mon, 6 Jan 2025 17:06:39 +0000 Subject: [PATCH 22/33] docs(readme): grammar fixes (#192) * docs(readme): grammar fixes Signed-off-by: Frazer Smith * kill me --------- Signed-off-by: Frazer Smith --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index de6079e..f2be7fe 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/) Fastify PostgreSQL connection plugin; with this, you can share the same PostgreSQL connection pool in every part of your server. -Under the hood [node-postgres](https://github.com/brianc/node-postgres) is used, the options that you pass to `register` will be passed to the PostgreSQL pool builder. +Under the hood [node-postgres](https://github.com/brianc/node-postgres) is used, and the options that you pass to `register` will be passed to the PostgreSQL pool builder. ## Install ``` @@ -150,7 +150,7 @@ fastify.listen({ port: 3000 }, err => { }) ``` -As you can see there is no need to close the client, since it is done internally. Promises and async await are supported as well. +As you can see there is no need to close the client since it is done internally. Promises and async await are supported as well. ### Name option If you need to have multiple databases set up, then you can name each one of them by passing `name: 'foo'`. It will then be accessible as `fastify.pg.foo`. @@ -182,7 +182,7 @@ fastify.listen({ port: 3000 }, err => { ### Native option If you want maximum performance you can install [pg-native](https://github.com/brianc/node-pg-native), and pass `native: true` to the plugin options. *Note: it requires PostgreSQL client libraries & tools installed, see [instructions](https://github.com/brianc/node-pg-native#install).* -Note: trying to use native options without successfully installation of `pg-native` will return a warning and fallback to regular `pg` module. +Note: trying to use native options without successful installation of `pg-native` will return a warning and fallback to the regular `pg` module. ```js const fastify = require('fastify')() @@ -208,7 +208,7 @@ fastify.listen({ port: 3000 }, err => { ``` ### `pg` option -If you want to provide your own `pg` module, for example to support packages like [`pg-range`](https://www.npmjs.com/package/pg-range), you can provide an optional `pg` option with the patched library to use: +If you want to provide your own `pg` module, for example, to support packages like [`pg-range`](https://www.npmjs.com/package/pg-range), you can provide an optional `pg` option with the patched library to use: ```js const fastify = require('fastify')() @@ -307,7 +307,7 @@ $ npm test DATABASE_TEST_URL="postgres://username:password@localhost/something_thats_a_test_database" npm test ``` -## Acknowledgements +## Acknowledgments This project is kindly sponsored by: - [nearForm](https://www.nearform.com) From d75b4f57dbdb10c9176df0c22a8bdef01ec8d69a Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Fri, 10 Jan 2025 18:41:50 +0000 Subject: [PATCH 23/33] docs(readme): add compatibility table (#193) Signed-off-by: Frazer Smith --- README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/README.md b/README.md index f2be7fe..d653750 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,21 @@ Under the hood [node-postgres](https://github.com/brianc/node-postgres) is used, ``` npm i pg @fastify/postgres ``` + +### Compatibility +| Plugin version | Fastify version | +| ---------------|-----------------| +| `^6.x` | `^5.x` | +| `^5.x` | `^4.x` | +| `^3.x` | `^3.x` | +| `^1.x` | `^2.x` | +| `^1.x` | `^1.x` | + + +Please note that if a Fastify version is out of support, then so are the corresponding versions of this plugin +in the table above. +See [Fastify's LTS policy](https://github.com/fastify/fastify/blob/main/docs/Reference/LTS.md) for more details. + ## Usage Add it to your project with `register` and you are done! This plugin will add the `pg` namespace to your Fastify instance, with the following properties: From 5f8483853d1672214e86fc7eaf934af512abc088 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Sat, 11 Jan 2025 08:01:32 +0000 Subject: [PATCH 24/33] build(deps-dev): replace standard with neostandard (#188) * build(deps-dev): replace standard with neostandard * chore: lint --- README.md | 2 +- eslint.config.js | 6 +++ examples/typescript/multiple-db/app.ts | 28 ++++++------ examples/typescript/single-db/app.ts | 20 ++++----- examples/typescript/transactions/app.ts | 46 +++++++++---------- index.d.ts | 24 +++++----- package.json | 6 +-- test/types/imports.test-d.ts | 12 ++--- test/types/initialization.test-d.ts | 32 +++++++------- test/types/query.test-d.ts | 32 +++++++------- test/types/transaction.test-d.ts | 59 +++++++++++++------------ 11 files changed, 137 insertions(+), 130 deletions(-) create mode 100644 eslint.config.js diff --git a/README.md b/README.md index d653750..2dd1ec5 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![CI](https://github.com/fastify/fastify-postgres/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/fastify/fastify-postgres/actions/workflows/ci.yml) [![NPM version](https://img.shields.io/npm/v/@fastify/postgres.svg?style=flat)](https://www.npmjs.com/package/@fastify/postgres) -[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/) +[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard) Fastify PostgreSQL connection plugin; with this, you can share the same PostgreSQL connection pool in every part of your server. Under the hood [node-postgres](https://github.com/brianc/node-postgres) is used, and the options that you pass to `register` will be passed to the PostgreSQL pool builder. diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 0000000..89fd678 --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,6 @@ +'use strict' + +module.exports = require('neostandard')({ + ignores: require('neostandard').resolveIgnoresFromGitignore(), + ts: true +}) diff --git a/examples/typescript/multiple-db/app.ts b/examples/typescript/multiple-db/app.ts index 4556843..e104b4d 100644 --- a/examples/typescript/multiple-db/app.ts +++ b/examples/typescript/multiple-db/app.ts @@ -1,37 +1,37 @@ -import fastify from 'fastify'; +import fastify from 'fastify' -import { fastifyPostgres } from '../../../index'; +import { fastifyPostgres } from '../../../index' -const app = fastify(); +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 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(); + sumClient.release() + subClient.release() return { sum: sumResult.rows, sub: subResult.rows, - }; -}); + } +}) -export { app }; +export { app } diff --git a/examples/typescript/single-db/app.ts b/examples/typescript/single-db/app.ts index a93182a..d08c31b 100644 --- a/examples/typescript/single-db/app.ts +++ b/examples/typescript/single-db/app.ts @@ -1,23 +1,23 @@ -import fastify from 'fastify'; +import fastify from 'fastify' -import { fastifyPostgres } from '../../../index'; +import { fastifyPostgres } from '../../../index' -const app = fastify(); +const app = fastify() app.register(fastifyPostgres, { connectionString: 'postgres://user:password@host:port/db', -}); +}) app.get('/calc', async () => { - const client = await app.pg.connect(); + const client = await app.pg.connect() - const sumResult = await client.query<{ sum: number }>('SELECT 2 + 2 as sum'); + const sumResult = await client.query<{ sum: number }>('SELECT 2 + 2 as sum') - client.release(); + client.release() return { sum: sumResult.rows, - }; -}); + } +}) -export { app }; +export { app } diff --git a/examples/typescript/transactions/app.ts b/examples/typescript/transactions/app.ts index 0ffe723..c9a57b4 100644 --- a/examples/typescript/transactions/app.ts +++ b/examples/typescript/transactions/app.ts @@ -1,12 +1,12 @@ -import fastify from 'fastify'; +import fastify from 'fastify' -import { fastifyPostgres } from '../../../index'; +import { fastifyPostgres } from '../../../index' -const app = fastify(); +const app = fastify() app.register(fastifyPostgres, { connectionString: 'postgres://user:password@host:port/db', -}); +}) app.post('/init-async', async () => { const createTableQuery = ` @@ -15,14 +15,14 @@ app.post('/init-async', async () => { name varchar(80) NOT NULL, created_at timestamp default NULL ); - `; + ` return app.pg.transact(async (client) => { - const result = await client.query(createTableQuery); + const result = await client.query(createTableQuery) - return result; - }); -}); + return result + }) +}) app.post('/init-cb', (_req, reply) => { const createTableQuery = ` @@ -31,22 +31,22 @@ app.post('/init-cb', (_req, reply) => { name varchar(80) NOT NULL, created_at timestamp default NULL ); - `; + ` app.pg.transact( (client) => { - return client.query(createTableQuery); + return client.query(createTableQuery) }, (error, result) => { if (error) { - reply.status(500).send(error); - return; + reply.status(500).send(error) + return } - reply.status(200).send(result); + reply.status(200).send(result) } - ); -}); + ) +}) app.post('/transact-route', { pg: { transact: true } }, async (req, _reply) => { const createTableQuery = ` @@ -55,10 +55,10 @@ app.post('/transact-route', { pg: { transact: true } }, async (req, _reply) => { name varchar(80) NOT NULL, created_at timestamp default NULL ); - `; + ` - return req.pg?.query(createTableQuery); -}); + return req.pg?.query(createTableQuery) +}) app.post( '/transact-route-alternate', @@ -70,10 +70,10 @@ app.post( name varchar(80) NOT NULL, created_at timestamp default NULL ); - `; + ` - return req.pg?.query(createTableQuery); + return req.pg?.query(createTableQuery) } -); +) -export { app }; +export { app } diff --git a/index.d.ts b/index.d.ts index e8bf52a..4516b96 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,5 +1,5 @@ -import { FastifyPluginCallback } from 'fastify'; -import * as Pg from 'pg'; +import { FastifyPluginCallback } from 'fastify' +import * as Pg from 'pg' declare module 'fastify' { export interface FastifyInstance { @@ -15,7 +15,7 @@ declare module 'fastify' { } } -type FastifyPostgres = FastifyPluginCallback; +type FastifyPostgres = FastifyPluginCallback declare namespace fastifyPostgres { export type PostgresDb = { @@ -24,11 +24,11 @@ declare namespace fastifyPostgres { query: Pg.Pool['query']; connect: Pg.Pool['connect']; transact: typeof transact; - }; + } export type FastifyPostgresRouteOptions = { transact: boolean | string; - }; + } export type PostgresPluginOptions = { /** @@ -45,20 +45,20 @@ declare namespace fastifyPostgres { * Instance name of fastify-postgres */ name?: string; - } & Pg.PoolConfig; + } & Pg.PoolConfig - export function transact( + export function transact ( fn: (client: Pg.PoolClient) => Promise - ): Promise; + ): Promise - export function transact( + export function transact ( fn: (client: Pg.PoolClient) => Promise, cb: (error: Error | null, result?: TResult) => void - ): void; + ): void export const fastifyPostgres: FastifyPostgres export { fastifyPostgres as default } } -declare function fastifyPostgres(...params: Parameters): ReturnType -export = fastifyPostgres \ No newline at end of file +declare function fastifyPostgres (...params: Parameters): ReturnType +export = fastifyPostgres diff --git a/package.json b/package.json index 5d0df4d..c90f491 100644 --- a/package.json +++ b/package.json @@ -7,8 +7,8 @@ "types": "index.d.ts", "scripts": { "check-examples": "tsc --build examples/typescript/*", - "lint": "standard", - "lint:fix": "standard --fix", + "lint": "eslint", + "lint:fix": "eslint --fix", "load-data": "docker exec -it fastify-postgres psql -c 'CREATE TABLE users(id serial PRIMARY KEY, username VARCHAR (50) NOT NULL);' -U postgres -d postgres", "postgres": "docker run -p 5432:5432 --name fastify-postgres -e POSTGRES_PASSWORD=postgres -d postgres:11-alpine", "test": "npm run test:unit && npm run test:typescript", @@ -71,9 +71,9 @@ "@types/pg": "^8.11.4", "c8": "^10.1.2", "fastify": "^5.0.0", + "neostandard": "^0.12.0", "pg": "^8.11.3", "pg-native": "^3.0.1", - "standard": "^17.1.0", "tsd": "^0.31.1", "typescript": "~5.7.2" }, diff --git a/test/types/imports.test-d.ts b/test/types/imports.test-d.ts index ca66dbe..e0e4016 100644 --- a/test/types/imports.test-d.ts +++ b/test/types/imports.test-d.ts @@ -1,6 +1,6 @@ -import defaultPluginImport from '../../index'; -import { - fastifyPostgres as namedPluginImport, - PostgresDb, - PostgresPluginOptions, -} from '../../index'; +/* eslint-disable @typescript-eslint/no-unused-vars */ +import defaultPluginImport, { + fastifyPostgres as namedPluginImport, + PostgresDb, + PostgresPluginOptions +} from '../../index' diff --git a/test/types/initialization.test-d.ts b/test/types/initialization.test-d.ts index 4063a77..00188d5 100644 --- a/test/types/initialization.test-d.ts +++ b/test/types/initialization.test-d.ts @@ -1,24 +1,24 @@ -import fastify from 'fastify'; -import * as pg from 'pg'; -import { expectAssignable, expectType } from 'tsd'; +import fastify from 'fastify' +import * as pg from 'pg' +import { expectAssignable, expectType } from 'tsd' -import fastifyPostgres, { PostgresDb } from '../../index'; +import fastifyPostgres, { PostgresDb } from '../../index' -const app = fastify(); +const app = fastify() // Without parameters -app.register(fastifyPostgres); -app.register(fastifyPostgres, {}); +app.register(fastifyPostgres) +app.register(fastifyPostgres, {}) // Own pg adapter -app.register(fastifyPostgres, { pg }); +app.register(fastifyPostgres, { pg }) // Native libpq wrapper -app.register(fastifyPostgres, { native: true }); +app.register(fastifyPostgres, { native: true }) // Multiple databases -app.register(fastifyPostgres, { name: 'users' }); -app.register(fastifyPostgres, { name: 'posts' }); +app.register(fastifyPostgres, { name: 'users' }) +app.register(fastifyPostgres, { name: 'posts' }) // Pool options app.register(fastifyPostgres, { @@ -27,13 +27,13 @@ app.register(fastifyPostgres, { database: 'mydb', password: 'secretpassword', port: 3211, -}); +}) app.register(fastifyPostgres, { connectionString: 'postgres://user:password@host:port/db', -}); +}) // Plugin property available app.after(() => { - expectAssignable(app.pg); - expectType(app.pg.users); -}); + expectAssignable(app.pg) + expectType(app.pg.users) +}) diff --git a/test/types/query.test-d.ts b/test/types/query.test-d.ts index d4cc201..d6b50bc 100644 --- a/test/types/query.test-d.ts +++ b/test/types/query.test-d.ts @@ -1,30 +1,30 @@ -import fastify from 'fastify'; -import { Client, Pool, PoolClient, QueryResult } from 'pg'; -import { expectAssignable, expectType } from 'tsd'; +import fastify from 'fastify' +import { Client, Pool, PoolClient, QueryResult } from 'pg' +import { expectAssignable, expectType } from 'tsd' -import fastifyPostgres, { PostgresDb } from '../../index'; +import fastifyPostgres, { PostgresDb } from '../../index' -const app = fastify(); +const app = fastify() app.register(fastifyPostgres, { connectionString: 'postgres://user:password@host:port/db', -}); +}) app.get('/calc', async () => { - expectAssignable(app.pg); + expectAssignable(app.pg) - expectType(app.pg.pool); - expectType(app.pg.Client); + expectType(app.pg.pool) + expectType(app.pg.Client) - const client = await app.pg.connect(); - expectType(client); + const client = await app.pg.connect() + expectType(client) - const sumResult = await client.query<{ sum: number }>('SELECT 2 + 2 as sum'); - expectType>(sumResult); + const sumResult = await client.query<{ sum: number }>('SELECT 2 + 2 as sum') + expectType>(sumResult) - client.release(); + client.release() return { sum: sumResult.rows, - }; -}); + } +}) diff --git a/test/types/transaction.test-d.ts b/test/types/transaction.test-d.ts index f56588b..77aee80 100644 --- a/test/types/transaction.test-d.ts +++ b/test/types/transaction.test-d.ts @@ -1,69 +1,70 @@ -import fastify from 'fastify'; -import { PoolClient, QueryResult } from 'pg'; -import { expectType } from 'tsd'; +import fastify from 'fastify' +import { PoolClient, QueryResult } from 'pg' +import { expectType } from 'tsd' -import fastifyPostgres, { PostgresDb } from '../../index'; +// eslint-disable-next-line @typescript-eslint/no-unused-vars +import fastifyPostgres, { PostgresDb } from '../../index' -const app = fastify(); +const app = fastify() app.register(fastifyPostgres, { connectionString: 'postgres://user:password@host:port/db', -}); +}) app.post('/insert-async', async () => { const insertQuery = ` INSERT INTO routes(name) VALUES ('ochakovo') RETURNING 1 + 1 as sum; - `; + ` const transactionResult = await app.pg.transact((client) => { - expectType(client); + expectType(client) - return client.query<{ sum: number }>(insertQuery); - }); + return client.query<{ sum: number }>(insertQuery) + }) - expectType>(transactionResult); + expectType>(transactionResult) - return transactionResult; -}); + return transactionResult +}) app.post('/insert-cb', (_req, reply) => { const insertQuery = ` INSERT INTO routes(name) VALUES ('ochakovo') RETURNING 1 + 1 as sum; - `; + ` app.pg.transact( (client) => { - expectType(client); + expectType(client) - return client.query<{ sum: number }>(insertQuery); + return client.query<{ sum: number }>(insertQuery) }, (error, result) => { - expectType(error); - expectType | undefined>(result); + expectType(error) + expectType | undefined>(result) if (error) { - reply.status(500).send(error); - return; + reply.status(500).send(error) + return } - reply.status(200).send(result); + reply.status(200).send(result) } - ); -}); + ) +}) app.post('/transact-route', { pg: { transact: true } }, async (req, _reply) => { const insertQuery = ` INSERT INTO routes(name) VALUES ('ochakovo') RETURNING 1 + 1 as sum; - `; + ` - return req.pg?.query(insertQuery); -}); + return req.pg?.query(insertQuery) +}) app.post( '/transact-route-alternate', @@ -73,8 +74,8 @@ app.post( INSERT INTO routes(name) VALUES ('ochakovo') RETURNING 1 + 1 as sum; - `; + ` - return req.pg?.query(insertQuery); + return req.pg?.query(insertQuery) } -); +) From 8c6e22795198e68ec0b9536fa59c5700484165d8 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Sat, 11 Jan 2025 08:02:01 +0000 Subject: [PATCH 25/33] 6.0.2 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index c90f491..3aeabe4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@fastify/postgres", - "version": "6.0.1", + "version": "6.0.2", "description": "Fastify PostgreSQL connection plugin", "main": "index.js", "type": "commonjs", From 2ce1a72b417bb7b1e63c671feaa8d92974c79e51 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Wed, 15 Jan 2025 15:30:05 +0000 Subject: [PATCH 26/33] build(dependabot): reduce npm updates to monthly (#194) --- .github/dependabot.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index dfa7fa6..35d66ca 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -9,5 +9,5 @@ updates: - package-ecosystem: "npm" directory: "/" schedule: - interval: "weekly" + interval: "monthly" open-pull-requests-limit: 10 From 08f35ad9fa07afcb6a5a9ab4d3c708dabb9cb334 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Mon, 3 Feb 2025 10:28:30 +0000 Subject: [PATCH 27/33] chore: rename master to main (#195) --- .github/workflows/ci.yml | 1 - README.md | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9d9f3b3..5a463a4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,6 @@ on: push: branches: - main - - master - next - 'v*' paths-ignore: diff --git a/README.md b/README.md index 2dd1ec5..91097d9 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # @fastify/postgres -[![CI](https://github.com/fastify/fastify-postgres/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/fastify/fastify-postgres/actions/workflows/ci.yml) +[![CI](https://github.com/fastify/fastify-postgres/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-postgres/actions/workflows/ci.yml) [![NPM version](https://img.shields.io/npm/v/@fastify/postgres.svg?style=flat)](https://www.npmjs.com/package/@fastify/postgres) [![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard) From 913c8c14629c43f5fb064fbdbaa81bd8e2942ec4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 1 Mar 2025 04:24:06 +0000 Subject: [PATCH 28/33] build(deps-dev): bump typescript from 5.7.3 to 5.8.2 (#196) Bumps [typescript](https://github.com/microsoft/TypeScript) from 5.7.3 to 5.8.2. - [Release notes](https://github.com/microsoft/TypeScript/releases) - [Changelog](https://github.com/microsoft/TypeScript/blob/main/azure-pipelines.release.yml) - [Commits](https://github.com/microsoft/TypeScript/compare/v5.7.3...v5.8.2) --- updated-dependencies: - dependency-name: typescript dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 3aeabe4..bdc47fc 100644 --- a/package.json +++ b/package.json @@ -75,7 +75,7 @@ "pg": "^8.11.3", "pg-native": "^3.0.1", "tsd": "^0.31.1", - "typescript": "~5.7.2" + "typescript": "~5.8.2" }, "peerDependencies": { "pg": ">=6.0.0" From e0085c268e8687baad02a16cb9f7d452d9582822 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Fri, 7 Mar 2025 19:12:22 +0000 Subject: [PATCH 29/33] ci(ci): set job permissions (#197) --- .github/workflows/ci.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5a463a4..2b9839d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,6 +16,9 @@ on: jobs: test: + permissions: + contents: write + pull-requests: write uses: fastify/workflows/.github/workflows/plugins-ci-postgres.yml@v5 with: license-check: true From 94d106cfdb7c4eb23312e01990d472f939d5b778 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Fri, 28 Mar 2025 06:40:35 +0000 Subject: [PATCH 30/33] docs(readme): update plugin version syntax (#198) --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 91097d9..d96ce68 100644 --- a/README.md +++ b/README.md @@ -15,11 +15,11 @@ npm i pg @fastify/postgres ### Compatibility | Plugin version | Fastify version | | ---------------|-----------------| -| `^6.x` | `^5.x` | +| `>=6.x` | `^5.x` | | `^5.x` | `^4.x` | -| `^3.x` | `^3.x` | -| `^1.x` | `^2.x` | -| `^1.x` | `^1.x` | +| `>=3.x <5.x` | `^3.x` | +| `>=1.x <3.x` | `^2.x` | +| `>=1.x <3.x` | `^1.x` | Please note that if a Fastify version is out of support, then so are the corresponding versions of this plugin From 26767eb97f013f746aacc7af48cdc9d8f82ae0c1 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Sun, 30 Mar 2025 21:55:23 +0100 Subject: [PATCH 31/33] ci: set permissions at workflow level (#199) --- .github/workflows/ci.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2b9839d..74fad4c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,11 +14,11 @@ on: - 'docs/**' - '*.md' +permissions: + contents: read + jobs: test: - permissions: - contents: write - pull-requests: write uses: fastify/workflows/.github/workflows/plugins-ci-postgres.yml@v5 with: license-check: true From 5ca3df3720a08d89e1a8fb8278bf85b2b644d3b1 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Sun, 30 Mar 2025 22:29:56 +0100 Subject: [PATCH 32/33] ci: restore job level permissions (#200) --- .github/workflows/ci.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 74fad4c..739c912 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,6 +19,9 @@ permissions: jobs: test: + permissions: + contents: write + pull-requests: write uses: fastify/workflows/.github/workflows/plugins-ci-postgres.yml@v5 with: license-check: true From 707e9fb0be9a9413c6311810aca88c9bf0accd92 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 1 May 2025 04:05:59 +0000 Subject: [PATCH 33/33] build(deps-dev): bump tsd from 0.31.2 to 0.32.0 (#201) Bumps [tsd](https://github.com/tsdjs/tsd) from 0.31.2 to 0.32.0. - [Release notes](https://github.com/tsdjs/tsd/releases) - [Commits](https://github.com/tsdjs/tsd/compare/v0.31.2...v0.32.0) --- updated-dependencies: - dependency-name: tsd dependency-version: 0.32.0 dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index bdc47fc..81fbac8 100644 --- a/package.json +++ b/package.json @@ -74,7 +74,7 @@ "neostandard": "^0.12.0", "pg": "^8.11.3", "pg-native": "^3.0.1", - "tsd": "^0.31.1", + "tsd": "^0.32.0", "typescript": "~5.8.2" }, "peerDependencies": {