Topics Fastify & Databases Knex.js Integration
intermediate 16 min read

Knex.js Integration

Add Knex.js query builder as a Fastify plugin for SQL database access.

Knex Plugin for Fastify

const Fastify = require('fastify');\nconst fp = require('fastify-plugin');\nconst knex = require('knex');\n\n// Database plugin\nasync function dbPlugin(fastify, opts) {\n  const db = knex({\n    client: 'pg',\n    connection: {\n      host: process.env.DB_HOST || 'localhost',\n      port: process.env.DB_PORT || 5432,\n      database: process.env.DB_NAME || 'myapp',\n      user: process.env.DB_USER || 'postgres',\n      password: process.env.DB_PASS || '',\n    },\n    pool: {\n      min: 2,\n      max: 10,\n    },\n    acquireConnectionTimeout: 10000,\n  });\n\n  // Decorate instance with db\n  fastify.decorate('db', db);\n\n  // Clean up on close\n  fastify.addHook('onClose', async (instance) => {\n    await instance.db.destroy();\n  });\n}\n\n// Register as fastify-plugin to share\napp.register(fp(dbPlugin, { name: 'database' }));\n\n// Usage in routes\napp.get('/api/users', async (request, reply) => {\n  const users = await app.db('users')\n    .select('*');\n    .where({ active: true })\n    .orderBy('created_at', 'desc')\n    .limit(20);\n\n  return { data: users };\n});

Examples

const Fastify = require('fastify');
const fp = require('fastify-plugin');
const knex = require('knex');

const app = Fastify({ logger: true });

// Database plugin
const dbPlugin = fp(async (fastify) => {
  const db = knex({
    client: 'pg',
    connection: {
      host: process.env.DB_HOST || 'localhost',
      database: process.env.DB_NAME || 'myapp',
      user: process.env.DB_USER || 'postgres',
      password: process.env.DB_PASS || '',
    },
  });

  fastify.decorate('db', db);
  fastify.addHook('onClose', () => db.destroy());
});

app.register(dbPlugin);

// User routes
app.get('/users', async (request) => {
  const { page = 1, limit = 10 } = request.query;
  const offset = (page - 1) * limit;

  const [users, total] = await Promise.all([
    app.db('users').limit(limit).offset(offset),
    app.db('users').count('* as total').first(),
  ]);

  return {
    data: users,
    meta: { page: Number(page), limit: Number(limit), total: Number(total.total) },
  };
});

app.listen({ port: 3000 });

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.