Skip to content

Instantly share code, notes, and snippets.

@jhunterkohler
Created May 26, 2022 20:24
Show Gist options
  • Save jhunterkohler/d3c9015794841543b5527b81bd54d24b to your computer and use it in GitHub Desktop.
Save jhunterkohler/d3c9015794841543b5527b81bd54d24b to your computer and use it in GitHub Desktop.
Idiomatic UUID type to avoid primitive obsession in object mapping. (typescript)
import crypto from "crypto";
const UUIDPattern =
/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;
export class InvalidUUIDError extends Error {
public get name() {
return this.constructor.name;
}
public constructor(public readonly value: string) {
super(`Invalid UUID: '${value}'`);
}
}
export class UUID {
static readonly pattern = UUIDPattern;
static readonly nil = new UUID("00000000-0000-0000-0000-000000000000");
private readonly _value: string;
public constructor(src?: string | UUID) {
if (typeof src == "undefined") {
this._value = crypto.randomUUID();
} else if (typeof src == "string") {
if (!UUIDPattern.test(src)) {
throw new Error(`Invalid UUID: '${src}'`);
}
this._value = src;
} else {
this._value = src._value;
}
}
public equals(other: string | UUID) {
return String(this) == String(other);
}
public toString() {
return this._value;
}
public toJSON() {
return this._value;
}
public isNil() {
return this.equals(UUID.nil);
}
}
export class UUIDTransformer {
public to(value: UUID) {
return String(value);
}
public from(value: string): UUID {
return new UUID(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment