Skip to content

Commit 8e258d3

Browse files
committed
feat(api): add enum validation utility for improved type safety
- Introduced `isValidEnumValue` and `validateEnumValue` functions to validate enum values, enhancing type safety in the application. - Updated `DisplayService` to utilize `validateEnumValue` for theme and unit properties, ensuring only valid enum values are assigned.
1 parent 4d74a5e commit 8e258d3

2 files changed

Lines changed: 23 additions & 4 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
export function isValidEnumValue<T extends Record<string, string | number>>(
2+
value: unknown,
3+
enumObject: T
4+
): value is T[keyof T] {
5+
if (value == null) {
6+
return false;
7+
}
8+
9+
return Object.values(enumObject).includes(value as T[keyof T]);
10+
}
11+
12+
export function validateEnumValue<T extends Record<string, string | number>>(
13+
value: unknown,
14+
enumObject: T
15+
): T[keyof T] | undefined {
16+
return isValidEnumValue(value, enumObject) ? (value as T[keyof T]) : undefined;
17+
}

api/src/unraid-api/graph/resolvers/info/display/display.service.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { type DynamixConfig } from '@app/core/types/ini.js';
66
import { toBoolean } from '@app/core/utils/casting.js';
77
import { fileExists } from '@app/core/utils/files/file-exists.js';
88
import { loadState } from '@app/core/utils/misc/load-state.js';
9+
import { validateEnumValue } from '@app/core/utils/validation/enum-validator.js';
910
import { getters } from '@app/store/index.js';
1011
import { ThemeName } from '@app/unraid-api/graph/resolvers/customization/theme.model.js';
1112
import { Display, Temperature } from '@app/unraid-api/graph/resolvers/info/display/display.model.js';
@@ -77,8 +78,8 @@ export class DisplayService {
7778
const display: Display = {
7879
id: 'info/display',
7980
case: caseInfo,
80-
theme: config.theme || ThemeName.white,
81-
unit: config.unit || Temperature.CELSIUS,
81+
theme: config.theme ?? ThemeName.white,
82+
unit: config.unit ?? Temperature.CELSIUS,
8283
scale: config.scale ?? false,
8384
tabs: config.tabs ?? true,
8485
resize: config.resize ?? true,
@@ -145,10 +146,11 @@ export class DisplayService {
145146
}
146147

147148
const { theme, unit, ...display } = state.display;
149+
148150
return {
149151
...display,
150-
theme: theme as ThemeName,
151-
unit: unit as Temperature,
152+
theme: validateEnumValue(theme, ThemeName),
153+
unit: validateEnumValue(unit, Temperature),
152154
scale: toBoolean(display.scale),
153155
tabs: toBoolean(display.tabs),
154156
resize: toBoolean(display.resize),

0 commit comments

Comments
 (0)