Skip to content
This repository has been archived by the owner on Sep 12, 2023. It is now read-only.

Commit

Permalink
intrn(query): make query to filter posts by time range
Browse files Browse the repository at this point in the history
  • Loading branch information
KennethTrecy committed Nov 13, 2022
1 parent 256f37a commit db24373
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
52 changes: 52 additions & 0 deletions database/queries/post/sift_by_range.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import Model from "%/models/post"
import Factory from "~/factories/post"

import pipe from "./sift_by_range"

describe("Database Pipe: Sift by range", () => {
it("can find inside time span", async() => {
const CURRENT_TIME = new Date()
const TIME_OFFSET = 10
const BEGIN_TIME = new Date()
BEGIN_TIME.setSeconds(CURRENT_TIME.getSeconds() - TIME_OFFSET)
const END_TIME = new Date()
END_TIME.setSeconds(CURRENT_TIME.getSeconds() + TIME_OFFSET * 2)
const model = await new Factory().insertOne()

const options = pipe({}, {
"filter": {
"dateTimeRange": {
"begin": BEGIN_TIME,
"end": END_TIME
}
}
})

const foundModels = await Model.findAll(options)

expect(foundModels).toHaveLength(1)
expect(foundModels).toHaveProperty("0.id", model.id)
})

it("cannot find outside time span", async() => {
const CURRENT_TIME = new Date()
const TIME_OFFSET = 5
const BEGIN_TIME = new Date()
BEGIN_TIME.setSeconds(CURRENT_TIME.getSeconds() - TIME_OFFSET * 2)
const END_TIME = new Date()
END_TIME.setSeconds(CURRENT_TIME.getSeconds() - TIME_OFFSET)
await new Factory().insertOne()

const options = pipe({}, {
"filter": {
"dateTimeRange": {
"begin": BEGIN_TIME,
"end": END_TIME
}
}
})
const foundModels = await Model.findAll(options)

expect(foundModels).toHaveLength(0)
})
})
38 changes: 38 additions & 0 deletions database/queries/post/sift_by_range.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type { FindOptions } from "%/types/dependent"
import type { DateTimeRangeFilter } from "$/types/query"

import Log from "$!/singletons/log"

import Condition from "%/helpers/condition"
import isUndefined from "$/type_guards/is_undefined"

/**
* Sift post models which within a certain range.
*/
export default function<T>(
currentState: FindOptions<T>,
constraints: DateTimeRangeFilter
): FindOptions<T> {
const newState = { ...currentState }

const { dateTimeRange } = constraints.filter

if (isUndefined(newState.where)) {
newState.where = {}
}

const condition = new Condition()
condition.and(
new Condition().greaterThanOrEqual("createdAt", dateTimeRange.begin),
new Condition().lessThanOrEqual("createdAt", dateTimeRange.end)
)

newState.where = new Condition().and(
new Condition(newState.where),
condition
).build()

Log.trace("pipeline", "sift by range")

return newState
}

0 comments on commit db24373

Please sign in to comment.