[feat] quick search function with typesense
This commit is contained in:
75
scripts/preload-searchindex.ts
Normal file
75
scripts/preload-searchindex.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { Client } from 'typesense';
|
||||
import chalk from 'chalk';
|
||||
import { db, poolConnection } from '../src/db/index.ts';
|
||||
import { client } from '../src/db/typesense.ts';
|
||||
|
||||
|
||||
async function createCollection(client: Client) {
|
||||
try {
|
||||
await client.collections('cards').retrieve();
|
||||
console.log(chalk.yellow('Collection "cards" already exists.'));
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.message.includes('404')) {
|
||||
await client.collections().create({
|
||||
name: 'cards',
|
||||
fields: [
|
||||
{ name: 'productId', type: 'int32' },
|
||||
{ name: 'productName', type: 'string' },
|
||||
{ name: 'productLineName', type: 'string' },
|
||||
{ name: 'rarityName', type: 'string' },
|
||||
{ name: 'setName', type: 'string' },
|
||||
{ name: 'cardType', type: 'string' },
|
||||
{ name: 'energyType', type: 'string' },
|
||||
{ name: 'number', type: 'string' },
|
||||
],
|
||||
default_sorting_field: 'productId',
|
||||
});
|
||||
console.log(chalk.green('Collection "cards" created successfully.'));
|
||||
} else {
|
||||
console.error(chalk.red('Error checking/creating collection:'), error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function preloadSearchIndex() {
|
||||
const pokemon = await db.query.cards.findMany({
|
||||
where: { productLineName: "pokemon" },
|
||||
//limit: 320,
|
||||
with: {
|
||||
set: true,
|
||||
}
|
||||
});
|
||||
|
||||
// Ensure the collection exists before importing documents
|
||||
await createCollection(client);
|
||||
|
||||
await client.collections('cards').documents().import(pokemon.map(card => ({
|
||||
productId: card.productId,
|
||||
productName: card.productName,
|
||||
productLineName: card.productLineName,
|
||||
rarityName: card.rarityName,
|
||||
setName: card.set?.setName || "",
|
||||
cardType: card.cardType || "",
|
||||
energyType: card.energyType || "",
|
||||
number: card.number,
|
||||
})), { action: 'upsert' });
|
||||
|
||||
console.log(chalk.green('Search index preloaded with Pokémon cards.'));
|
||||
|
||||
}
|
||||
|
||||
await preloadSearchIndex().catch((error) => {
|
||||
console.error(chalk.red('Error preloading search index:'), error);
|
||||
for (const e of error.importResults) {
|
||||
if (!e.success) {
|
||||
console.error(chalk.red(`Error importing document ${e.id}:`), e.error);
|
||||
}
|
||||
}
|
||||
process.exit(1);
|
||||
}).finally(() => {
|
||||
poolConnection.end();
|
||||
console.log(chalk.blue('Database connection closed.'));
|
||||
process.exit(0);
|
||||
});
|
||||
Reference in New Issue
Block a user