All files / src/validators InputValidator.ts

100% Statements 22/22
100% Branches 10/10
100% Functions 6/6
100% Lines 22/22

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 57 58 59 60 61 62 63 64 65 66 67                                12x   12x   12x   12x 104x     96x   96x 92x 90x 71x   19x     4x       96x 96x 2x 2x   94x   2x 2x             56x       8x       25x      
/* 
  Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
  
  Licensed under the Apache License, Version 2.0 (the "License").
  You may not use this file except in compliance with the License.
  You may obtain a copy of the License at
  
      http://www.apache.org/licenses/LICENSE-2.0
  
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
import { APIGatewayProxyEvent } from 'aws-lambda';
import RuleConfigError from 'src/common/RuleConfigError';
 
export const REGEX_DESCRIPTION = /^[ 0-9a-zA-Z_-\s]{1,1000}$/;
 
export const REGEX_ID = /^[:0-9a-zA-Z_-]{1,100}$/;
 
export abstract class InputValidator<T> {
    public readonly errors: string[] = [];
 
    async parseAndValidate(event: APIGatewayProxyEvent): Promise<T> {
        const body = this.parse(event);
 
        if (body) {
            await this.validate(body);
            if (this.errors.length > 0) {
                throw new RuleConfigError(this.errors.join(', '), 400, false);
            }
            return body;
        }
 
        throw new RuleConfigError(this.errors.join(', '), 400, false);
    }
 
    protected parse(event: APIGatewayProxyEvent): T | null {
        try {
            if (!event.body) {
                this.errors.push('Request body cannot be null or empty.');
                return null;
            }
            return <T>JSON.parse(event.body.toString());
        } catch (error) {
            this.errors.push('Request body contains invalid JSON.');
            return null;
        }
    }
 
    protected abstract validate(input: T): Promise<void>;
 
    protected isBlank(input: string): boolean {
        return !input || /^\s*$/.test(input);
    }
 
    protected isValidDescriptionName(description?: string): boolean {
        return !description || REGEX_DESCRIPTION.test(description);
    }
 
    protected isValidId(id: string): boolean {
        return REGEX_ID.test(id);
    }
}