forked from diplodoc-platform/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidator.ts
73 lines (62 loc) · 2.26 KB
/
validator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import {Arguments} from 'yargs';
import {join, resolve} from 'path';
import {readFileSync} from 'fs';
import {load} from 'js-yaml';
import log from '@doc-tools/transform/lib/log';
function notEmptyStringValidator(value: string): Boolean {
return Boolean(value) && Boolean(value?.length);
}
function requiredValueValidator(value: unknown): Boolean {
return Boolean(value);
}
interface ValidatorProps {
errorMessage?: string;
validateFn?: (value: any) => Boolean;
defaultValue?: any;
}
const validators: Record<string, ValidatorProps> = {
'storageEndpoint': {
errorMessage: 'Endpoint of S3 storage must be provided when publishes.',
validateFn: notEmptyStringValidator,
},
'storageBucket': {
errorMessage: 'Bucket name of S3 storage must be provided when publishes.',
validateFn: notEmptyStringValidator,
},
'storageKeyId': {
errorMessage: 'Key Id of S3 storage must be provided when publishes.',
validateFn: notEmptyStringValidator,
defaultValue: process.env.YFM_STORAGE_KEY_ID,
},
'storageSecretKey': {
errorMessage: 'Secret key of S3 storage must be provided when publishes.',
validateFn: notEmptyStringValidator,
defaultValue: process.env.YFM_STORAGE_SECRET_KEY,
},
};
export function argvValidator(argv: Arguments<Object>): Boolean {
try {
// Combine passed argv and properties from configuration file.
const pathToConfig = argv.config ? String(argv.config) : join(String(argv.input), '.yfm');
const content = readFileSync(resolve(pathToConfig), 'utf8');
Object.assign(argv, load(content) || {});
} catch (error) {
if (error.name === 'YAMLException') {
log.error(`Error to parse .yfm: ${error.message}`);
}
}
if (argv.publish) {
for (const [field, validator] of Object.entries(validators)) {
const value = argv[field] ?? validator.defaultValue;
if (!validator) {
continue;
}
const validateFn = validator.validateFn ?? requiredValueValidator;
if (!validateFn(value)) {
throw new Error(validator.errorMessage);
}
argv[field] = value;
}
}
return true;
}