Files
property-management-network/app/api/search/route.ts
T

66 lines
2.0 KiB
TypeScript
Raw Normal View History

import { NextRequest, NextResponse } from "next/server"
import { and, eq, ilike, or } from "drizzle-orm"
import { db } from "@/lib/db"
import { tenants, properties, maintenance_requests } from "@/lib/db/schema"
import { getSessionUser } from "@/lib/session"
export async function GET(req: NextRequest) {
const user = await getSessionUser()
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
const q = req.nextUrl.searchParams.get("q")?.trim() ?? ""
if (q.length < 2) return NextResponse.json({ tenants: [], properties: [], maintenance: [] })
const like = `%${q}%`
const [tenantRows, propertyRows, maintenanceRows] = await Promise.all([
db
.select({
id: tenants.id,
first_name: tenants.first_name,
last_name: tenants.last_name,
email: tenants.email,
status: tenants.status,
})
.from(tenants)
.where(
and(
eq(tenants.user_id, user.id),
or(ilike(tenants.first_name, like), ilike(tenants.last_name, like), ilike(tenants.email, like))
)
)
.limit(5),
db
.select({
id: properties.id,
name: properties.name,
address_line1: properties.address_line1,
city: properties.city,
})
.from(properties)
.where(
and(
eq(properties.user_id, user.id),
or(ilike(properties.name, like), ilike(properties.address_line1, like), ilike(properties.city, like))
)
)
.limit(5),
db
.select({
id: maintenance_requests.id,
title: maintenance_requests.title,
status: maintenance_requests.status,
priority: maintenance_requests.priority,
})
.from(maintenance_requests)
.where(and(eq(maintenance_requests.user_id, user.id), ilike(maintenance_requests.title, like)))
.limit(5),
])
return NextResponse.json({
tenants: tenantRows,
properties: propertyRows,
maintenance: maintenanceRows,
})
}