A Fastify plugin that uses the PostgreSQL client, Slonik. Slonik abstracts repeating code patterns, protects against unsafe connection handling and value interpolation, and provides a rich debugging experience.
For fastify v4, use latest version, for fastify v3, use v1.4x.
Yarn
yarn add fastify-slonik
NPM
npm i fastify-slonik
PNPM
pnpm i fastify-slonik
Both default export and named export option is available.
// index.js
const { fastifySlonik } = require("fastify-slonik");
// Or
const fastifySlonik = require("fastify-slonik");
or
import { fastifySlonik } from "fastify-slonik";
// or
import fastifySlonik from "fastify-slonik";
// register fastify-slonik
try {
await app.register(fastifySlonik, {
connectionString: process.env.DATABASE_URL,
});
} catch (err) {
console.log("🔴 Failed to connect, check your Connection string");
throw new Error(err);
}
FastifyInstance (this) and FastifyRequest (request) have been decorated with slonik and sql. Use it the way you want.
// setup test route
// The decorated Fastify server is bound to this in route route handlers:
fastify.get('/users', async function (this, request, reply) {
const { sql, slonik } = this;
const queryText = sql`SELECT * FROM users WHERE user_id = 1`
const user = await slonik.query(queryText)
reply.send(user)
}
fastify.get('/users', async function (request, reply) {
const { sql, slonik } = request
const queryText = sql`SELECT * FROM users WHERE user_id = 1`
const user = await slonik.query(queryText)
reply.send(user)
}
View Slonik API for details.
Tap is used for testing. Use pnpm test
command to run tests.
$ docker-compose up
To run the tests:
- Create .env
cp .env.example .env
$ yarn test
- Set up a database of your choice in a postgres server of your choice
- Create the required table using
CREATE TABLE users(id serial PRIMARY KEY, username VARCHAR (50) NOT NULL);
- Create .env
cp .env.example .env
and update environment variables accordingly
Licensed under MIT.