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

Commit

Permalink
intrn(validator): make validator to ensure there are no user
Browse files Browse the repository at this point in the history
  • Loading branch information
KennethTrecy committed Dec 6, 2022
1 parent b5db48b commit 11d5ca4
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
3 changes: 1 addition & 2 deletions database/managers/role.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { Pipe } from "$/types/database"
import type { Serializable } from "$/types/general"
import type { RoleQueryParameters } from "$/types/query"
import type { Model as BaseModel, ModelCtor, FindAndCountOptions } from "%/types/dependent"
import type { RoleAttributes, RoleResourceIdentifier } from "$/types/documents/role"
import type { Model as BaseModel, ModelCtor, FindAndCountOptions } from "%/types/dependent"

import User from "%/models/user"
import Model from "%/models/role"
Expand All @@ -12,7 +12,6 @@ import AttachedRole from "%/models/attached_role"
import RoleTransformer from "%/transformers/role"

import Condition from "%/helpers/condition"
import trimRight from "$/string/trim_right"
import makeUnique from "$/array/make_unique"
import segregateIDsExistentially from "%/helpers/segregate_IDs_existentially"

Expand Down
43 changes: 43 additions & 0 deletions server/validators/manager/do_not_have_any_owned_user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import type { Request } from "!/types/dependent"
import type { ValidationState, ValidationConstraints } from "!/types/validation"
import type { DepartmentIdentifierListDocument } from "$/types/documents/department"

import Manager from "%/managers/department"

/**
* Validator to check if department still has user.
*
* Note: The validator only works for resources with numerical department IDs only.
*/
export default async function(
currentState: Promise<ValidationState>,
constraints: ValidationConstraints<Request>
): Promise<ValidationState> {
const state = await currentState

if (state.maySkip) return state

const manager = new Manager(constraints.request)

const modelID = state.value
const departments = await manager.countUsers([ modelID ]) as DepartmentIdentifierListDocument
const hasNoUser = departments.data[0].meta.userCount === 0

if (hasNoUser) return state

const error = {
"field": constraints.field,
"friendlyName": constraints.friendlyName,
"messageMaker": (
field: string,
value: string
) => {
const subject = `The "${field}" with a value of "${value}"`
const predicate = "should have no existing user."

return `${subject} ${predicate}`
}
}

throw error
}

0 comments on commit 11d5ca4

Please sign in to comment.