Skip to content

Commit

Permalink
Avoid duplicated sql expressions (#327)
Browse files Browse the repository at this point in the history
* Avoid duplicated sql expressions

* Fixerino capuccino
  • Loading branch information
dBianchii authored May 11, 2024
1 parent 03bda8f commit baaa5bd
Showing 1 changed file with 30 additions and 60 deletions.
90 changes: 30 additions & 60 deletions src/app/_lib/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { unstable_noStore as noStore } from "next/cache"
import { db } from "@/db"
import { tasks, type Task } from "@/db/schema"
import type { DrizzleWhere } from "@/types"
import { and, asc, count, desc, gte, lte, or } from "drizzle-orm"
import { and, asc, count, desc, gte, lte, or, type SQL } from "drizzle-orm"

import { filterColumn } from "@/lib/filter-column"

Expand All @@ -30,66 +30,36 @@ export async function getTasks(input: GetTasksSchema) {
const fromDay = from ? new Date(from) : undefined
const toDay = to ? new Date(to) : undefined

const expressions: (SQL<unknown> | undefined)[] = [
title
? filterColumn({
column: tasks.title,
value: title,
})
: undefined,
// Filter tasks by status
!!status
? filterColumn({
column: tasks.status,
value: status,
isSelectable: true,
})
: undefined,
// Filter tasks by priority
!!priority
? filterColumn({
column: tasks.priority,
value: priority,
isSelectable: true,
})
: undefined,
// Filter by createdAt
fromDay && toDay
? and(gte(tasks.createdAt, fromDay), lte(tasks.createdAt, toDay))
: undefined,
]
const where: DrizzleWhere<Task> =
!operator || operator === "and"
? and(
// Filter tasks by title
title
? filterColumn({
column: tasks.title,
value: title,
})
: undefined,
// Filter tasks by status
!!status
? filterColumn({
column: tasks.status,
value: status,
isSelectable: true,
})
: undefined,
// Filter tasks by priority
!!priority
? filterColumn({
column: tasks.priority,
value: priority,
isSelectable: true,
})
: undefined,
// Filter by createdAt
fromDay && toDay
? and(gte(tasks.createdAt, fromDay), lte(tasks.createdAt, toDay))
: undefined
)
: or(
// Filter tasks by title
title
? filterColumn({
column: tasks.title,
value: title,
})
: undefined,
// Filter tasks by status
!!status
? filterColumn({
column: tasks.status,
value: status,
isSelectable: true,
})
: undefined,
// Filter tasks by priority
!!priority
? filterColumn({
column: tasks.priority,
value: priority,
isSelectable: true,
})
: undefined,
// Filter by createdAt
fromDay && toDay
? and(gte(tasks.createdAt, fromDay), lte(tasks.createdAt, toDay))
: undefined
)
!operator || operator === "and" ? and(...expressions) : or(...expressions)

// Transaction is used to ensure both queries are executed in a single transaction
const { data, total } = await db.transaction(async (tx) => {
Expand Down

0 comments on commit baaa5bd

Please sign in to comment.