npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

fastify-multi-db-query-builder

v1.0.13

Published

Query Builder untuk Fastify yang mendukung MongoDB dan SQL database

Downloads

102

Readme

Fastify DB Query Builder

Query Builder untuk Fastify yang dapat mengkonversi query ke format yang sesuai dengan database engine yang digunakan (MongoDB atau SQL via Knex).

Instalasi

npm install fastify-multi-db-query-builder

Registrasi Plugin

const fastify = require('fastify')();

// Registrasi plugin
fastify.register(require('fastify-multi-db-query-builder'), {
  decoratorName: 'queryBuilder', // default
  dbEngine: 'pg', // default, bisa 'mongodb', 'mysql', 'sqlite', 'mssql'
  dbDecorator: 'pg' // default, nama decorator untuk database
});

Cara Penggunaan yang Benar

1. Menggunakan fastify.db() sebagai Function

// Cara 1: fastify.db() tanpa parameter
const users = await fastify.db()
  .from('users')
  .select('id', 'name', 'email')
  .where('status', 'active')
  .get();

// Cara 2: fastify.db() dengan table name
const users = await fastify.db('users')
  .select('id', 'name', 'email')
  .where('status', 'active')
  .get();

2. Helper Methods

// Query untuk SQL database
const sqlUsers = await fastify.db.sql('users')
  .where('status', 'active')
  .get();

// Query untuk MongoDB
const mongoUsers = await fastify.db.mongo('users')
  .where('status', 'active')
  .get();

// Query dengan engine default
const defaultUsers = await fastify.db.query('users')
  .where('status', 'active')
  .get();

3. Contoh Penggunaan dalam Hook

fastify.addHook('preHandler', async (request, reply) => {
  const apiKey = request.headers['x-api-token'];
  const appKey = request.headers['x-app-key'];
  
  // Menggunakan fastify.db() untuk query
  const app = await fastify.db('d_application')
    .where('uid_user_system', apiKey)
    .where('app_key', appKey)
    .first();
  
  if (!app) {
    return reply.status(401).send({ status: false, message: 'Invalid API key' });
  }
  
  request.app = app;
});

4. Helper Functions

async function getApp(fastify, apiKey, appKey) {
  return await fastify.db('d_application')
    .where('uid_user_system', apiKey)
    .where('app_key', appKey)
    .first();
}

async function getUser(fastify, userId) {
  return await fastify.db('users')
    .where('id', userId)
    .first();
}

async function getPackage(fastify, packageId) {
  if (process.env.DB_ENGINE === 'mongodb') {
    return await fastify.mongoose.Packages.findById(packageId).lean();
  }
  return await fastify.db('packages')
    .where('id', packageId)
    .first();
}

Penggunaan Global (Tanpa Fastify)

Library ini juga dapat digunakan secara global tanpa harus selalu mendaftarkan Knex/Mongoose terlebih dahulu. Berikut adalah berbagai cara penggunaannya:

1. Global Registration

const { QueryBuilder } = require('fastify-multi-db-query-builder');
const KnexAdapter = require('fastify-multi-db-query-builder/lib/adapters/knexAdapter');
const MongoAdapter = require('fastify-multi-db-query-builder/lib/adapters/mongoAdapter');

// Setup Knex secara global
const knex = require('knex')({
  client: 'pg',
  connection: {
    host: 'localhost',
    user: 'postgres',
    password: 'password',
    database: 'testdb'
  }
});

// Mendaftarkan Knex secara global
KnexAdapter.registerGlobal(knex, 'db');

// Setup Mongoose secara global
const mongoose = require('mongoose');
MongoAdapter.registerGlobal(mongoose, 'default');

// Sekarang bisa menggunakan QueryBuilder tanpa fastify
const mockFastify = {};

// Query SQL
const sqlBuilder = new QueryBuilder(mockFastify, { dbEngine: 'pg' });
const users = await sqlBuilder
  .from('users')
  .select('id', 'name', 'email')
  .where('status', 'active')
  .get();

// Query MongoDB
const mongoBuilder = new QueryBuilder(mockFastify, { dbEngine: 'mongodb' });
const mongoUsers = await mongoBuilder
  .from('users')
  .select('name', 'email', 'status')
  .where('status', 'active')
  .get();

2. Environment Variables

// Set environment variables
process.env.DB_CLIENT = 'pg';
process.env.DB_HOST = 'localhost';
process.env.DB_PORT = '5432';
process.env.DB_USER = 'postgres';
process.env.DB_PASSWORD = 'password';
process.env.DB_NAME = 'testdb';
process.env.MONGO_URI = 'mongodb://localhost:27017/testdb';

const mockFastify = {};

// Query SQL menggunakan environment variables
const sqlBuilder = new QueryBuilder(mockFastify, { dbEngine: 'pg' });
const users = await sqlBuilder
  .from('users')
  .select('id', 'name')
  .where('status', 'active')
  .get();

// Query MongoDB menggunakan environment variables
const mongoBuilder = new QueryBuilder(mockFastify, { dbEngine: 'mongodb' });
const mongoUsers = await mongoBuilder
  .from('users')
  .select('name', 'email')
  .where('status', 'active')
  .get();

3. Config Registration

// Mendaftarkan konfigurasi database
KnexAdapter.registerConfig({
  client: 'pg',
  connection: {
    host: 'localhost',
    user: 'postgres',
    password: 'password',
    database: 'testdb'
  }
}, 'main');

MongoAdapter.registerConfig({
  uri: 'mongodb://localhost:27017/testdb',
  options: {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }
}, 'main');

const mockFastify = {
  dbConfig: global.dbConfigs?.main,
  mongoConfig: global.mongoConfigs?.main
};

// Query SQL menggunakan config
const sqlBuilder = new QueryBuilder(mockFastify, { dbEngine: 'pg' });
const users = await sqlBuilder
  .from('users')
  .select('id', 'name')
  .where('status', 'active')
  .get();

// Query MongoDB menggunakan config
const mongoBuilder = new QueryBuilder(mockFastify, { dbEngine: 'mongodb' });
const mongoUsers = await mongoBuilder
  .from('users')
  .select('name', 'email')
  .where('status', 'active')
  .get();

4. Mixed Approach (SQL + MongoDB)

// Setup Knex untuk SQL
const knex = require('knex')({
  client: 'pg',
  connection: {
    host: 'localhost',
    user: 'postgres',
    password: 'password',
    database: 'testdb'
  }
});

// Setup Mongoose untuk MongoDB
const mongoose = require('mongoose');
await mongoose.connect('mongodb://localhost:27017/testdb');

// Mendaftarkan keduanya secara global
KnexAdapter.registerGlobal(knex, 'main');
MongoAdapter.registerGlobal(mongoose, 'main');

const mockFastify = {};

// Query SQL
const sqlBuilder = new QueryBuilder(mockFastify, { dbEngine: 'pg' });
const sqlUsers = await sqlBuilder
  .from('users')
  .select('id', 'name', 'email')
  .where('status', 'active')
  .limit(5)
  .get();

// Query MongoDB
const mongoBuilder = new QueryBuilder(mockFastify, { dbEngine: 'mongodb' });
const mongoUsers = await mongoBuilder
  .from('users')
  .select('name', 'email', 'status')
  .where('status', 'active')
  .limit(5)
  .get();

// Insert data ke SQL
const newSqlUser = await sqlBuilder
  .from('users')
  .insert({
    name: 'John Doe',
    email: '[email protected]',
    status: 'active'
  });

// Insert data ke MongoDB
const newMongoUser = await mongoBuilder
  .from('users')
  .insert({
    name: 'Jane Doe',
    email: '[email protected]',
    status: 'active',
    createdAt: new Date()
  });

Fitur

  • ✅ Mendukung MongoDB dan SQL database (PostgreSQL, MySQL, SQLite, MSSQL) melalui Knex
  • ✅ API yang konsisten untuk semua database engine
  • ✅ Konversi otomatis query ke format yang sesuai
  • ✅ Mendukung operasi dasar CRUD (Create, Read, Update, Delete)
  • ✅ Plugin Fastify yang mudah digunakan
  • ✅ Helper methods untuk database yang berbeda
  • Penggunaan global tanpa Fastify
  • Auto-initialization dari environment variables
  • Config registration untuk setup yang fleksibel
  • fastify.db() sebagai function

Cara Penggunaan

1. Query Builder Dasar

// Menggunakan query builder dengan engine default
const users = await fastify.queryBuilder()
  .from('users')
  .where('status', 'active')
  .get();

// Menggunakan query builder dengan engine tertentu
const mongoUsers = await fastify.queryBuilder({ dbEngine: 'mongodb' })
  .from('users')
  .where('status', 'active')
  .get();

2. Helper Methods

// Query untuk SQL database (PostgreSQL, MySQL, SQLite, MSSQL)
const sqlUsers = await fastify.db.sql('users')
  .where('status', 'active')
  .get();

// Query untuk MongoDB
const mongoUsers = await fastify.db.mongo('users')
  .where('status', 'active')
  .get();

// Query dengan engine default
const defaultUsers = await fastify.db.query('users')
  .where('status', 'active')
  .get();

3. Query dengan Engine Tertentu

// Mendapatkan query builder dengan engine tertentu
const pgQuery = fastify.getQueryBuilder('pg');
const mongoQuery = fastify.getQueryBuilder('mongodb');

const users = await pgQuery.from('users').get();
const mongoUsers = await mongoQuery.from('users').get();

API Reference

Query Builder Methods

from(tableName)

Menentukan tabel atau koleksi yang akan digunakan.

fastify.queryBuilder().from('users')

where(field, operator, value)

Menambahkan kondisi where.

// Format 1: where(field, value)
fastify.queryBuilder().from('users').where('status', 'active')

// Format 2: where(field, operator, value)
fastify.queryBuilder().from('users').where('age', '>', 18)

// Format 3: where({field1: value1, field2: value2})
fastify.queryBuilder().from('users').where({status: 'active', age: 18})

whereIn(field, values)

Menambahkan kondisi where dengan operator IN.

fastify.queryBuilder().from('users').whereIn('role', ['admin', 'user'])

whereNotIn(field, values)

Menambahkan kondisi where dengan operator NOT IN.

fastify.queryBuilder().from('users').whereNotIn('role', ['admin'])

whereLike(field, value)

Menambahkan kondisi where dengan operator LIKE.

fastify.queryBuilder().from('users').whereLike('name', '%john%')

select(...fields)

Menentukan field yang akan diambil.

fastify.queryBuilder().from('users').select('id', 'name', 'email')

orderBy(field, direction)

Mengurutkan hasil query.

fastify.queryBuilder().from('users').orderBy('created_at', 'desc')

limit(limit)

Membatasi jumlah hasil.

fastify.queryBuilder().from('users').limit(10)

skip(skip) / offset(offset)

Melewati sejumlah hasil.

fastify.queryBuilder().from('users').skip(20)
// atau
fastify.queryBuilder().from('users').offset(20)

Execution Methods

get()

Mengeksekusi query dan mendapatkan semua hasil.

const users = await fastify.queryBuilder().from('users').get()

first()

Mengeksekusi query dan mendapatkan hasil pertama.

const user = await fastify.queryBuilder().from('users').where('id', 1).first()

insert(data)

Menyisipkan data baru.

// Menyisipkan satu data
const newUser = await fastify.queryBuilder().from('users').insert({
  name: 'John Doe',
  email: '[email protected]'
})

// Menyisipkan banyak data
const newUsers = await fastify.queryBuilder().from('users').insert([
  { name: 'John Doe', email: '[email protected]' },
  { name: 'Jane Doe', email: '[email protected]' }
])

update(data)

Memperbarui data.

const updatedCount = await fastify.queryBuilder()
  .from('users')
  .where('id', 1)
  .update({ name: 'John Updated' })

delete()

Menghapus data.

const deletedCount = await fastify.queryBuilder()
  .from('users')
  .where('id', 1)
  .delete()

count(field)

Menghitung jumlah data.

const userCount = await fastify.queryBuilder()
  .from('users')
  .where('status', 'active')
  .count()

toSQL() (hanya untuk SQL database)

Mendapatkan query SQL.

const sql = fastify.queryBuilder()
  .from('users')
  .where('status', 'active')
  .toSQL()
console.log(sql) // SELECT * FROM "users" WHERE "status" = 'active'

Konfigurasi

Query Builder akan menggunakan konfigurasi database yang sudah ada di aplikasi:

  • Untuk MongoDB, menggunakan koneksi Mongoose yang sudah terdaftar di Fastify
  • Untuk SQL database, menggunakan koneksi Knex yang sudah terdaftar di Fastify

Environment Variables

# Database engine default
DB_ENGINE=pg # atau mongodb, mysql, sqlite, mssql

# Knex decorator name (jika menggunakan Knex)
DB_DECORATOR=db

Contoh Penggunaan dalam Route

// Route untuk mendapatkan semua user
fastify.get('/users', async (request, reply) => {
  try {
    const users = await fastify.queryBuilder()
      .from('users')
      .select('id', 'name', 'email')
      .where('status', 'active')
      .orderBy('created_at', 'desc')
      .limit(10)
      .get();

    return { success: true, data: users };
  } catch (error) {
    reply.code(500);
    return { success: false, error: error.message };
  }
});

// Route untuk membuat user baru
fastify.post('/users', async (request, reply) => {
  try {
    const userData = request.body;
    
    const newUser = await fastify.queryBuilder()
      .from('users')
      .insert(userData);

    reply.code(201);
    return { success: true, data: newUser };
  } catch (error) {
    reply.code(500);
    return { success: false, error: error.message };
  }
});

Dependencies

Library ini memerlukan dependencies berikut:

  • fastify (peer dependency)
  • knex (untuk SQL database)
  • mongoose (untuk MongoDB)

License

MIT