57 lines
1.5 KiB
TypeScript
57 lines
1.5 KiB
TypeScript
import { FastifyInstance } from "fastify"
|
|
import { db } from "../db"
|
|
import { customers, projects, timeEntries, users } from "../db/schema"
|
|
import { ilike, and, eq } from "drizzle-orm"
|
|
import { z } from "zod"
|
|
|
|
export default async function searchRoutes(fastify: FastifyInstance) {
|
|
fastify.addHook("preHandler", async (request, reply) => {
|
|
try {
|
|
await request.jwtVerify()
|
|
} catch (err) {
|
|
return reply.code(401).send({ message: "Unauthorized" })
|
|
}
|
|
})
|
|
|
|
fastify.get("/", async (request, reply) => {
|
|
const { q } = request.query as { q?: string }
|
|
|
|
if (!q || q.length < 2) {
|
|
return { timeEntries: [], customers: [], projects: [], users: [] }
|
|
}
|
|
|
|
const searchTerm = `%${q}%`
|
|
|
|
const [customerResults, projectResults, timeEntryResults, userResults] = await Promise.all([
|
|
db
|
|
.select()
|
|
.from(customers)
|
|
.where(and(eq(customers.active, true), ilike(customers.name, searchTerm)))
|
|
.limit(10),
|
|
db
|
|
.select()
|
|
.from(projects)
|
|
.where(and(eq(projects.active, true), ilike(projects.name, searchTerm)))
|
|
.limit(10),
|
|
db
|
|
.select()
|
|
.from(timeEntries)
|
|
.where(ilike(timeEntries.description, searchTerm))
|
|
.limit(10),
|
|
db
|
|
.select()
|
|
.from(users)
|
|
.where(
|
|
ilike(users.name, searchTerm) || ilike(users.email, searchTerm)
|
|
)
|
|
.limit(10)
|
|
])
|
|
|
|
return {
|
|
customers: customerResults,
|
|
projects: projectResults,
|
|
timeEntries: timeEntryResults,
|
|
users: userResults
|
|
}
|
|
})
|
|
} |