Для начальной загрузки нашего приложения у нас есть конфигурация, хранящаяся в файле JSON. Эта конфигурация содержит различные настройки, такие как определение конечных точек (например, шлюз API или SMS и т. Д.) Или некоторые значения по умолчанию для входа в систему.
endpoint.ts
export const isEndpoint = (candidate: any): candidate is Endpoint => {
return (
candidate && typeof candidate === 'object' &&
candidate.hasOwnProperty('protocol') && (candidate.protocol === null || ['http', 'https'].includes(candidate.protocol)) &&
candidate.hasOwnProperty('address') && (candidate.address === null || typeof candidate.address === 'string') &&
candidate.hasOwnProperty('port') && (candidate.port === null || typeof candidate.port === 'number') &&
candidate.hasOwnProperty('path') && (candidate.path === null || typeof candidate.path === 'string')
);
}
export interface Endpoint {
protocol: 'http'|'https'|null,
address: string|null,
port: number|null,
path: string|null,
}
configutation.ts
import { Endpoint, isEndpoint } from './endpoint';
export const isConfiguration = (candidate: any): candidate is Configuration => {
return (
candidate && typeof candidate === 'object' &&
candidate.hasOwnProperty('endpoints') &&
candidate.endpoints.hasOwnProperty('api') && isEndpoint(candidate.endpoints.api) &&
candidate.endpoints.hasOwnProperty('smsGateway') && isEndpoint(candidate.endpoints.smsGateway) &&
candidate.hasOwnProperty('auth') &&
candidate.auth.hasOwnProperty('company') && (candidate.auth.company === null || typeof candidate.auth.company === 'string')
);
}
export interface Configuration {
endpoints: {
api: Endpoint,
smsGateway: Endpoint
},
auth: {
company: string|null
}
}
В конце концов, код используется в сервисе Angular следующим образом:
get configuration$(): Observable<Configuration> {
if (this.configutation$) {
return this.configutation$;
}
const path = environment.configuration;
this.configutation$ = this.http.get<any>(path).pipe(
map(configutation => {
if (isConfigutation(configutation)) {
return configutation;
}
throw new Error('Configutation is broken.');
}),
shareReplay(1),
catchError(error => {
console.log(error);
return of(null);
})
);
return this.configutation$;
}
Теперь isEndpoint а также isConfiguration Методы кажутся очень громоздкими, особенно когда конфигурация растет. Я думал об использовании схемы JSON и проверке ввода по файлу схемы. Но если кто-то заменит этот файл, например, во время сборки, он все равно может пойти не так.
Можно ли это улучшить?
Это способ TypeScrpt или как это можно улучшить?
