Skip to content

Commit edbdc97

Browse files
use zod for validation
1 parent 5b35e2a commit edbdc97

File tree

1 file changed

+19
-35
lines changed

1 file changed

+19
-35
lines changed

src/context/FrontendConfigContext.tsx

Lines changed: 19 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { ReactNode, createContext, use } from 'react';
22
import { DocLinkCreator } from '../lib/shared/links';
3+
import { z } from 'zod';
34

45
export enum Landscape {
56
Live = 'LIVE',
@@ -61,41 +62,24 @@ export const useFrontendConfig = () => {
6162
return context;
6263
};
6364

65+
const OidcConfigSchema = z.object({
66+
clientId: z.string(),
67+
issuerUrl: z.string(),
68+
scopes: z.array(z.string()),
69+
});
70+
71+
const FrontendConfigSchema = z.object({
72+
backendUrl: z.string(),
73+
gatewayUrl: z.string(),
74+
documentationBaseUrl: z.string(),
75+
oidcConfig: OidcConfigSchema,
76+
landscape: z.optional(z.nativeEnum(Landscape)),
77+
});
78+
6479
function validateAndCastFrontendConfig(config: unknown): FrontendConfig {
65-
if (typeof config !== 'object' || config === null) {
66-
throw new Error('Invalid frontend config');
67-
}
68-
const castedConfig = config as FrontendConfig;
69-
if (!castedConfig.backendUrl) {
70-
throw new Error('Invalid frontend config: missing backendUrl');
71-
}
72-
if (!castedConfig.gatewayUrl) {
73-
throw new Error('Invalid frontend config: missing gatewayUrl');
74-
}
75-
if (!castedConfig.documentationBaseUrl) {
76-
throw new Error('Invalid frontend config: missing documentationBaseUrl');
77-
}
78-
if (!castedConfig.oidcConfig) {
79-
throw new Error('Invalid frontend config: missing oidcConfig');
80-
}
81-
if (typeof castedConfig.oidcConfig !== 'object' || castedConfig.oidcConfig === null) {
82-
throw new Error('Invalid frontend config: oidcConfig is not an object');
80+
try {
81+
return FrontendConfigSchema.parse(config);
82+
} catch (error) {
83+
throw new Error(`Invalid frontend config: ${error}`);
8384
}
84-
if (!castedConfig.oidcConfig.clientId) {
85-
throw new Error('Invalid frontend config: missing clientId in oidcConfig');
86-
}
87-
if (!castedConfig.oidcConfig.issuerUrl) {
88-
throw new Error('Invalid frontend config: missing issuerUrl in oidcConfig');
89-
}
90-
if (!castedConfig.oidcConfig.scopes) {
91-
throw new Error('Invalid frontend config: missing scopes in oidcConfig');
92-
}
93-
if (!Array.isArray(castedConfig.oidcConfig.scopes)) {
94-
throw new Error('Invalid frontend config: scopes in oidcConfig is not an array');
95-
}
96-
if (castedConfig.landscape && !Object.values(Landscape).includes(castedConfig.landscape)) {
97-
throw new Error('Invalid frontend config: invalid landscape');
98-
}
99-
100-
return castedConfig;
10185
}

0 commit comments

Comments
 (0)