feat: Set withDeleted as true if filtering on deleted_at in modules (#6626)

Similar convention already existed in v1, so we are just applying this for the abstract module factory
This commit is contained in:
Stevche Radevski
2024-03-08 12:40:00 +01:00
committed by GitHub
parent 272fb6d328
commit 056e3e9599
4 changed files with 67 additions and 6 deletions

View File

@@ -3,12 +3,20 @@ import { deduplicate, isDefined, isObject } from "../common"
import { SoftDeletableFilterKey } from "../dal"
// Following convention here is fine, we can make it configurable if needed.
const DELETED_AT_FIELD_NAME = "deleted_at"
type FilterFlags = {
withDeleted?: boolean
}
export function buildQuery<T = any, TDto = any>(
filters: Record<string, any> = {},
config: FindConfig<TDto> & { primaryKeyFields?: string | string[] } = {}
): DAL.FindOptions<T> {
const where: DAL.FilterQuery<T> = {}
buildWhere(filters, where)
const filterFlags: FilterFlags = {}
buildWhere(filters, where, filterFlags)
const primaryKeyFieldArray = isDefined(config.primaryKeyFields)
? !Array.isArray(config.primaryKeyFields)
@@ -43,7 +51,7 @@ export function buildQuery<T = any, TDto = any>(
findOptions.orderBy = config.order as DAL.OptionsQuery<T>["orderBy"]
}
if (config.withDeleted) {
if (config.withDeleted || filterFlags.withDeleted) {
findOptions.filters ??= {}
findOptions.filters[SoftDeletableFilterKey] = {
withDeleted: true,
@@ -61,12 +69,20 @@ export function buildQuery<T = any, TDto = any>(
return { where, options: findOptions }
}
function buildWhere(filters: Record<string, any> = {}, where = {}) {
function buildWhere(
filters: Record<string, any> = {},
where = {},
flags: FilterFlags = {}
) {
for (let [prop, value] of Object.entries(filters)) {
if (prop === DELETED_AT_FIELD_NAME) {
flags.withDeleted = true
}
if (["$or", "$and"].includes(prop)) {
where[prop] = value.map((val) => {
const deepWhere = {}
buildWhere(val, deepWhere)
buildWhere(val, deepWhere, flags)
return deepWhere
})
continue
@@ -80,7 +96,7 @@ function buildWhere(filters: Record<string, any> = {}, where = {}) {
if (isObject(value)) {
where[prop] = {}
buildWhere(value, where[prop])
buildWhere(value, where[prop], flags)
continue
}