| 1 | import type { Database } from "../db";
|
|---|
| 2 | import {buildsTable, componentsTable } from "../schema";
|
|---|
| 3 | import {and, desc, eq, ilike} from "drizzle-orm";
|
|---|
| 4 |
|
|---|
| 5 | export async function getAllComponents(db: Database, limit?: number, q?: string, componentType?: string) {
|
|---|
| 6 | let queryConditions = [];
|
|---|
| 7 |
|
|---|
| 8 | if (q) {
|
|---|
| 9 | queryConditions.push(
|
|---|
| 10 | ilike(componentsTable.name, `%${q}%`)
|
|---|
| 11 | );
|
|---|
| 12 | }
|
|---|
| 13 |
|
|---|
| 14 | if(componentType && componentType.trim() !== 'all') {
|
|---|
| 15 | queryConditions.push(
|
|---|
| 16 | eq(componentsTable.type, componentType.trim().toLowerCase())
|
|---|
| 17 | );
|
|---|
| 18 | }
|
|---|
| 19 |
|
|---|
| 20 | const componentsList = await db
|
|---|
| 21 | .select({
|
|---|
| 22 | id: componentsTable.id,
|
|---|
| 23 | name: componentsTable.name,
|
|---|
| 24 | brand: componentsTable.brand,
|
|---|
| 25 | price: componentsTable.price,
|
|---|
| 26 | })
|
|---|
| 27 | .from(componentsTable)
|
|---|
| 28 | .where(
|
|---|
| 29 | queryConditions.length > 0 ?
|
|---|
| 30 | and (
|
|---|
| 31 | ...queryConditions
|
|---|
| 32 | )
|
|---|
| 33 | : undefined
|
|---|
| 34 | )
|
|---|
| 35 | .orderBy(
|
|---|
| 36 | desc(componentsTable.price)
|
|---|
| 37 | )
|
|---|
| 38 | .limit(limit || 100); // 100 placeholder
|
|---|
| 39 |
|
|---|
| 40 | return componentsList;
|
|---|
| 41 | }
|
|---|
| 42 |
|
|---|
| 43 | export async function getComponentDetails(db: Database, componentId: number) {
|
|---|
| 44 | const [componentDetails] = await db
|
|---|
| 45 | .select()
|
|---|
| 46 | .from(componentsTable)
|
|---|
| 47 | .where(
|
|---|
| 48 | eq(componentsTable.id, componentId)
|
|---|
| 49 | )
|
|---|
| 50 | .limit(1);
|
|---|
| 51 |
|
|---|
| 52 | return componentDetails ?? null;
|
|---|
| 53 | } |
|---|