diff --git a/examples/typescript/transactions/app.ts b/examples/typescript/transactions/app.ts index 636ec59..0ffe723 100644 --- a/examples/typescript/transactions/app.ts +++ b/examples/typescript/transactions/app.ts @@ -48,4 +48,32 @@ app.post('/init-cb', (_req, reply) => { ); }); +app.post('/transact-route', { pg: { transact: true } }, async (req, _reply) => { + const createTableQuery = ` + CREATE TABLE routes ( + id bigserial primary key, + name varchar(80) NOT NULL, + created_at timestamp default NULL + ); + `; + + return req.pg?.query(createTableQuery); +}); + +app.post( + '/transact-route-alternate', + { pg: { transact: 'primary' } }, + async (req, _reply) => { + const createTableQuery = ` + CREATE TABLE routes ( + id bigserial primary key, + name varchar(80) NOT NULL, + created_at timestamp default NULL + ); + `; + + return req.pg?.query(createTableQuery); + } +); + export { app }; diff --git a/index.d.ts b/index.d.ts index 8dacfdc..d6ea691 100644 --- a/index.d.ts +++ b/index.d.ts @@ -18,6 +18,10 @@ type PostgresDb = { transact: typeof transact; }; +type FastifyPostgresRouteOptions = { + transact: boolean | string; +}; + type PostgresPluginOptions = { /** * Custom pg @@ -41,6 +45,14 @@ declare module 'fastify' { export interface FastifyInstance { pg: PostgresDb & Record; } + + export interface FastifyRequest { + pg?: Pg.PoolClient; + } + + export interface RouteShorthandOptions { + pg?: FastifyPostgresRouteOptions; + } } export { fastifyPostgres, PostgresDb, PostgresPluginOptions }; diff --git a/test/types/transaction.test-d.ts b/test/types/transaction.test-d.ts index a48841a..f56588b 100644 --- a/test/types/transaction.test-d.ts +++ b/test/types/transaction.test-d.ts @@ -54,3 +54,27 @@ app.post('/insert-cb', (_req, reply) => { } ); }); + +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); +}); + +app.post( + '/transact-route-alternate', + { pg: { transact: 'primary' } }, + async (req, _reply) => { + const insertQuery = ` + INSERT INTO routes(name) + VALUES ('ochakovo') + RETURNING 1 + 1 as sum; + `; + + return req.pg?.query(insertQuery); + } +);