All files proto-table-builder.ts

100% Statements 20/20
100% Branches 10/10
100% Functions 3/3
100% Lines 18/18

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  1x                     10x   1x 13x 2x     11x 1x     10x 1x               1x 13x   9x 9x 26x   10x           10x 10x     9x    
import { ProtoTable } from './ProtoTable';
import { DYNAMIC_SIZE_TYPE, staticTypes } from './types';
 
export type FieldName = string;
export type FieldType = string;
export type TypedFieldsMap = Map<FieldName, FieldType>;
 
/**
 * Dynamic Types
 * - should be prefixed with UInt32BE describing the memory space requirements.
 * Example of dynamic types: String, BSON.
 */
const getDynamicSizeField = (fieldName: string) => `${fieldName}_SIZE`;
 
const validate = (typedFields: TypedFieldsMap) => {
    if (typedFields === null || typeof typedFields === 'undefined') {
        throw new Error('Typed fields cannot be null or undefined.');
    }
 
    if(!(typedFields instanceof Map)) {
        throw new TypeError('The typed fields should be an instance of Map<string, string>');
    }
 
    if(typedFields.size === 0) {
        throw new RangeError('No typed fields found. Please use decorators @proto, @uint8, @string, @object, etc.');
    }
};
 
/**
 * Returns ProtoTable describing types of given fields.
 * @param { TypedFieldsMap } typedFields - mapping between feilds and their types.
 */
export function build(typedFields: TypedFieldsMap): ProtoTable {
    validate(typedFields);
 
    const protoTable: ProtoTable = [];
    for (let [field, type] of typedFields.entries()) {
        if (staticTypes.has(type)) protoTable.push([field, type]);
        else {
            const dsField = getDynamicSizeField(field);
 
            /** Example:
             * [ 'requestId_SIZE', 'UInt32BE' ], 
             * [ 'requestId',      'requestId_SIZE',   'String' ],
             */
            protoTable.push([dsField,   DYNAMIC_SIZE_TYPE]);
            protoTable.push([field,     dsField,            type]);
        }
    }
    return protoTable;
}