Merge branch 'typesense-search-engine' into fix-bugs

This commit is contained in:
2025-04-25 22:00:11 +03:30
9 changed files with 146 additions and 28 deletions
@@ -151,6 +151,81 @@ const deleteTransaction = async (transactionId) => {
return null
}
const ensureCollectionExists = async () => {
const collections = await client.collections().retrieve()
const collectionExists = collections.some((collection) => collection.name === 'transactions')
if (collectionExists) {
await client.collections('transactions').delete()
}
const schema = getTypeSenseSchema()
await client.collections().create(schema)
console.log('Collection "transactions" created successfully')
}
const searchTransactions = async (inputQuery) => {
const tsFeatures = new TsApiFeatures(client, 'transactions', inputQuery).filter().facet().sort().limitFields().paginate().search()
let { facets, items, totalCount, pagesCount } = await tsFeatures.execute()
return { facets, transactions: items, totalCount, pagesCount }
}
const indexAllTransactions = async () => {
const batchSize = 20
const count = await Transaction.countDocuments({}, null)
const rounds = Math.ceil(count / batchSize)
await ensureCollectionExists()
for (let i = 1; i <= rounds; i++) {
console.log(`Indexing ${batchSize} transactions, Round ${i}`)
const transactions = await Transaction.find({}, null, null)
.skip((i - 1) * batchSize)
.limit(batchSize)
let documents = []
for (const transaction of transactions) {
const data = {
_id: transaction._id,
type: transaction.type,
status: transaction.status,
source: transaction.source,
value: transaction.value,
description: transaction.description,
createdAt: Math.floor(new Date(transaction.createdAt).getTime() / 1000), // Store as timestamp in seconds
}
documents.push(data)
}
await client.collections('transactions').documents().import(documents, { action: 'emplace' })
}
return { totalCount: count }
}
const getTypeSenseSchema = () => {
return {
name: 'transactions',
enable_nested_fields: true,
fields: [
{ name: '_id', type: 'string', facet: false, infix: false },
{ name: 'type', type: 'string', facet: false },
{ name: 'status', type: 'string', facet: false },
{ name: 'source', type: 'string', facet: false },
{ name: 'value', type: 'int64', facet: false },
{ name: 'description', type: 'string', facet: false, infix: true },
{ name: 'createdAt', type: 'int64', facet: false },
],
default_sorting_field: 'createdAt',
}
}
module.exports = {
createTransaction,
getUserTransaction,
@@ -158,4 +233,6 @@ module.exports = {
updateTransaction,
deleteTransaction,
getTransactionByBelongingId,
indexAllTransactions,
searchTransactions,
}