UNPKG

fuzzy-search-lib

Version:

A flexible fuzzy search library supporting both MongoDB and PostgreSQL

61 lines 2.33 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PostgreSQLAdapter = void 0; const pg_1 = require("pg"); const helpers_1 = require("../utils/helpers"); const algorithms_1 = require("../algorithms"); class PostgreSQLAdapter { constructor(connectionString, tableName) { this.client = null; this.connectionString = connectionString; this.tableName = tableName; } async connect() { if (!this.client) { this.client = new pg_1.Client(this.connectionString); await this.client.connect(); } } async disconnect() { if (this.client) { await this.client.end(); this.client = null; } } async search(query, options) { if (!this.client) { throw new Error('Database not connected. Call connect() first.'); } // Default options const threshold = options.threshold ?? 0.5; const limit = options.limit ?? 10; const offset = options.offset ?? 0; const algorithm = options.algorithm ?? 'levenshtein'; // Construct SELECT query to get all records // In a production implementation, you would likely want to optimize this const selectQuery = `SELECT * FROM ${this.tableName}`; const result = await this.client.query(selectQuery); const allRecords = result.rows; // Calculate scores for each record const scoredRecords = allRecords.map((record) => { const score = (0, helpers_1.calculateMatchScore)(record, query, options.fields, algorithms_1.algorithms[algorithm].calculate); return { item: record, score }; }); // Filter by threshold and sort by score const filteredRecords = scoredRecords .filter(({ score }) => score >= threshold) .sort((a, b) => b.score - a.score); // Apply pagination const paginatedRecords = filteredRecords.slice(offset, offset + limit); return { items: paginatedRecords.map(({ item }) => item), total: filteredRecords.length, limit, offset, threshold, query }; } } exports.PostgreSQLAdapter = PostgreSQLAdapter; //# sourceMappingURL=postgresql.js.map