Skip to content

Instantly share code, notes, and snippets.

@lkostrowski
Created April 2, 2021 09:24
Show Gist options
  • Save lkostrowski/7430cea8872d49ff8f0ca178ec646f19 to your computer and use it in GitHub Desktop.
Save lkostrowski/7430cea8872d49ff8f0ca178ec646f19 to your computer and use it in GitHub Desktop.
export declare namespace SystemID {
/**
* System short public ID, e.g A10005, B00040
*/
export type Short = string & {
__brand: 'system-short-id';
};
/**
* UUID V4
*/
export type UUID = string & {
__brand: 'system-uuid';
};
}
const uuidRegex = new RegExp(
/^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,
);
const shortIDRegex = new RegExp(/^[A-Z]\d{5}$/);
export abstract class SystemID {
static createShortID(id: string): SystemID.Short {
if (!SystemID.validateShortId(id)) {
throw new Error('Invalid short ID provided');
}
return (id as unknown) as SystemID.Short;
}
static createUUID(id: string): SystemID.UUID {
if (!SystemID.validateUUID(id)) {
throw new Error('Invalid UUID provided');
}
return (id as unknown) as SystemID.UUID;
}
private static validateShortId(id: string) {
return shortIDRegex.test(id);
}
private static validateUUID(id: string) {
return uuidRegex.test(id);
}
static isUUID(id: string | SystemID.Short | SystemID.UUID): id is SystemID.UUID {
return SystemID.validateUUID(id as string);
}
static isShortID(id: string | SystemID.Short | SystemID.UUID): id is SystemID.Short {
return SystemID.validateShortId(id as string);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment