This repository has been archived by the owner on Sep 12, 2023. It is now read-only.
generated from KennethTrecy/web_template
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
intrn(validator): make validator to ensure there are no user
- Loading branch information
1 parent
b5db48b
commit 11d5ca4
Showing
2 changed files
with
44 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |