UNPKG

1.99 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const expression_1 = require("@gabliam/expression");
4const _ = require("lodash");
5const constants_1 = require("./constants");
6const errors_1 = require("./errors");
7const joi_1 = require("./joi");
8/**
9 * Validate a value
10 * @param {string} path
11 * @param {any} value
12 * @param {ValueValidator} validator
13 */
14function valueValidator(path, value, validator) {
15 const options = Object.assign({ abortEarly: false }, (validator.options || {}));
16 const validate = joi_1.Joi.validate(value, validator.schema, options);
17 if (validate.error) {
18 if (validator.throwError) {
19 const msg = validator.customErrorMsg || `Error for '${path}' value`;
20 throw new errors_1.ValueValidationError(msg, validate.error);
21 }
22 else {
23 return null;
24 }
25 }
26 return validate.value;
27}
28/**
29 * Create value extractor
30 * @param {Container} container
31 */
32function configureValueExtractor(container) {
33 /**
34 * Get value in configuration
35 * @param {string} path
36 * @param {any} defaultValue
37 * @param {ValueValidator|null} validator?
38 * @returns any
39 */
40 return (path, defaultValue, validator) => {
41 let value = undefined;
42 const config = container.get(constants_1.APP_CONFIG);
43 try {
44 const expression = new expression_1.ExpressionParser(config).parseExpression(path);
45 value = expression.getValue();
46 }
47 catch (_a) { }
48 if (value === undefined) {
49 value = _.get(config, path, defaultValue);
50 }
51 try {
52 if (validator) {
53 value = valueValidator(path, value, validator);
54 }
55 return value;
56 }
57 catch (err) {
58 if (err instanceof errors_1.ValueValidationError) {
59 throw err;
60 }
61 }
62 };
63}
64exports.configureValueExtractor = configureValueExtractor;