-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsample.ts
More file actions
64 lines (55 loc) · 1.56 KB
/
Copy pathsample.ts
File metadata and controls
64 lines (55 loc) · 1.56 KB
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
import validateModel from './validator.ts';
export class CreateUserCommand {
// Required
username: string = "";
// Optional
email: string | null = null;
}
function runSample(
input: {[key: string]: any},
validateFunc?: (target: CreateUserCommand, validationErrors: Array<string>) => boolean
) {
const [command, isValid, validationErrors] = validateModel(CreateUserCommand, input, validateFunc);
console.log('Input: ', JSON.stringify(input));
console.log('Validated command: ', JSON.stringify(command));
if (isValid) {
console.log('OK');
} else {
console.log('Error(s): ', JSON.stringify(validationErrors));
}
console.log('-------------------------------------------------')
}
// Missing keys
runSample({});
// OK
runSample({
username: 'Rincewind'
});
// OK
runSample({
username: 'Rincewind',
email: 'rince@wind.com'
});
// Overpost!
runSample({
username: 'Overpost!',
email: 'over@post.com',
overpost: 'An additional field!'
});
// Additional validations
runSample({
username: 'bad',
email: 'rince@wind.com',
},
// You can send a function that receives:
// - target: mapped model
// - validationErrors: an array where you can add error messages
// And returns a boolean indicating if the model is valid or not.
(target: CreateUserCommand, validationErrors: Array<string>): boolean => {
let isValid = true;
if (target.username.length < 5) {
isValid = false;
validationErrors.push('username must contain at least 5 characters');
}
return isValid;
});