All files / src/lib/util/validators constraint-types.ts

96.77% Statements 30/31
100% Branches 7/7
85.71% Functions 6/7
95.83% Lines 23/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 5766x   66x         66x     66x 3x     66x 11x     66x 4x   4x   4x 3x         66x       66x       4x 12x     4x   3x 2x 1x       2x 2x 1x          
import semver from 'semver';
 
import {
    constraintDateTypeSchema,
    constraintNumberTypeSchema,
    constraintStringTypeSchema,
} from '../../schema/constraint-value-types';
import BadDataError from '../../error/bad-data-error';
import { ILegalValue } from '../../types/stores/context-field-store';
 
export const validateNumber = async (value: unknown): Promise<void> => {
    await constraintNumberTypeSchema.validateAsync(value);
};
 
export const validateString = async (value: unknown): Promise<void> => {
    await constraintStringTypeSchema.validateAsync(value);
};
 
export const validateSemver = (value: unknown): void => {
    const cleanValue = semver.clean(value) === value;
 
    const result = semver.valid(value);
 
    if (result && cleanValue) return;
    throw new BadDataError(
        `the provided value is not a valid semver format. The value provided was: ${value}`,
    );
};
 
export const validateDate = async (value: unknown): Promise<void> => {
    await constraintDateTypeSchema.validateAsync(value);
};
 
export const validateLegalValues = (
    legalValues: Readonly<ILegalValue[]>,
    match: string[] | string,
): void => {
    const legalStrings = legalValues.map((legalValue) => {
        return legalValue.value;
    });
 
    if (Array.isArray(match)) {
        // Compare arrays to arrays
        const valid = match.every((value) => legalStrings.includes(value));
        if (!valid)
            throw new BadDataError(
                `input values are not specified as a legal value on this context field`,
            );
    } else {
        const valid = legalStrings.includes(match);
        if (!valid)
            throw new BadDataError(
                `${match} is not specified as a legal value on this context field`,
            );
    }
};