From 44d241813b74d38a6be3e2245cc17e0130e3b269 Mon Sep 17 00:00:00 2001 From: MohammadHMazarei Date: Tue, 22 Apr 2025 13:01:22 +0330 Subject: [PATCH] ADD: indexAllTransactions and searchTransactions services --- components/transaction/transactionService.js | 75 ++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/components/transaction/transactionService.js b/components/transaction/transactionService.js index 864ba5a..88cbc4b 100644 --- a/components/transaction/transactionService.js +++ b/components/transaction/transactionService.js @@ -151,6 +151,79 @@ 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, + } + + 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 }, + ], + default_sorting_field: 'createdAt', + } +} + module.exports = { createTransaction, getUserTransaction, @@ -158,4 +231,6 @@ module.exports = { updateTransaction, deleteTransaction, getTransactionByBelongingId, + indexAllTransactions, + searchTransactions, }