All files / src/types Guid.ts

100% Statements 9/9
100% Branches 1/1
100% Functions 4/4
100% Lines 9/9

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 411x       1x     8x       4x 4x 2x 2x       5x       3x                                    
import { v4 as generateUUID } from 'uuid';
import type { Flattable } from './Flattable';
import type { ITypeBuilder } from '../typeBuilder';
 
export class Guid implements Flattable<Guid.Flatten> {
 
    public constructor(
        public readonly guidString: string
    ) {}
 
    public static from(value: string): Guid {
        const regex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/u;
        if (!regex.test(value))
            throw new Error('Could not parse Guid, guid string is invalid.');
        return new Guid(value.toLowerCase());
    }
 
    public static generate(): Guid {
        return new Guid(generateUUID());
    }
 
    public get flatten(): Guid.Flatten {
        return this.guidString;
    }
}
 
// istanbul ignore next
export namespace Guid {
 
    export type Flatten = string;
 
    export class TypeBuilder implements ITypeBuilder<Flatten, Guid> {
 
        public build(value: Flatten): Guid {
            return Guid.from(value);
        }
    }
 
    export const builder = new TypeBuilder();
}