@localsecurity/name-id
Version:
A utility to create and parse lexicographically sortable ID's with embeded model names and created timestamp
324 lines • 12.4 kB
TypeScript
import { Model } from "@localsecurity/types";
/**
* Models // todo -> add Models / ModelNames enum to types package
* */
declare enum Models {
ActivityLog = "ActivityLog",
Address = "Address",
AppliedCameraPlan = "AppliedCameraPlan",
AppliedLivePatrol = "AppliedLivePatrol",
AppliedOperatorMinutes = "AppliedOperatorMinutes",
AppliedProduct = "AppliedProduct",
AppliedSetupFee = "AppliedSetupFee",
AudioCustomMessageType = "AudioCustomMessageType",
AuditLog = "AuditLog",
CallLog = "CallLog",
CallNotice = "CallNotice",
Camera = "Camera",
CameraAccessUrls = "CameraAccessUrls",
CameraCredentials = "CameraCredentials",
CameraEvent = "CameraEvent",
CameraImmixConfig = "CameraImmixConfig",
CameraPlan = "CameraPlan",
CameraQualitySettings = "CameraQualitySettings",
CameraSceneDetectionResult = "CameraSceneDetectionResult",
CameraSceneDetectionResultItem = "CameraSceneDetectionResultItem",
CameraSceneDetectionSettings = "CameraSceneDetectionSettings",
CameraSceneDetectionThreshold = "CameraSceneDetectionThreshold",
Contact = "Contact",
Customer = "Customer",
CustomerUserPermission = "CustomerUserPermission",
CustomerUserPermissionSet = "CustomerUserPermissionSet",
DashboardDetail = "DashboardDetail",
EmailLog = "EmailLog",
ExchangeRateSetting = "ExchangeRateSetting",
Incident = "Incident",
IncidentActionDetail = "IncidentActionDetail",
IncidentActionList = "IncidentActionList",
IncidentBundleTime = "IncidentBundleTime",
IncidentCodeDetail = "IncidentCodeDetail",
IncidentDataToShare = "IncidentDataToShare",
IncidentNote = "IncidentNote",
IncidentShareActionItems = "IncidentShareActionItems",
IncidentShareContactInformation = "IncidentShareContactInformation",
IncidentShareEntry = "IncidentShareEntry",
IncidentShareEntryAccess = "IncidentShareEntryAccess",
IncidentShareEntyNote = "IncidentShareEntyNote",
IncidentShareEvent = "IncidentShareEvent",
IncidentShareIntegrator = "IncidentShareIntegrator",
IncidentShareSettings = "IncidentShareSettings",
IncidentShareSite = "IncidentShareSite",
Invoice = "Invoice",
InvoicePayment = "InvoicePayment",
InvoiceTransferPayment = "InvoiceTransferPayment",
LivePatrol = "LivePatrol",
Master = "Master",
Notification = "Notification",
NotificationSetting = "NotificationSetting",
ObjectGroup = "ObjectGroup",
OperatorMinutes = "OperatorMinutes",
PaymentTransferSettings = "PaymentTransferSettings",
Phone = "Phone",
ProcedureTask = "ProcedureTask",
Product = "Product",
RapidSOSActivity = "RapidSOSActivity",
RapidSOSAttachment = "RapidSOSAttachment",
RapidSOSCivicAddress = "RapidSOSCivicAddress",
RapidSOSDetails = "RapidSOSDetails",
RapidSOSEmergencyContact = "RapidSOSEmergencyContact",
RapidSOSEventDetails = "RapidSOSEventDetails",
RapidSOSIncident = "RapidSOSIncident",
RapidSOSLocation = "RapidSOSLocation",
RapidSOSLogMessage = "RapidSOSLogMessage",
RspndrActivity = "RspndrActivity",
RspndrEvents = "RspndrEvents",
RspndrIncident = "RspndrIncident",
RspndrIncidentCheckItem = "RspndrIncidentCheckItem",
RspndrIncidentGroundingRule = "RspndrIncidentGroundingRule",
SMSLog = "SMSLog",
SOP = "SOP",
SecondaryCameraEvent = "SecondaryCameraEvent",
SetupFee = "SetupFee",
SignalTestLog = "SignalTestLog",
Site = "Site",
SiteEmergencyContact = "SiteEmergencyContact",
SiteIntegration = "SiteIntegration",
SiteSubscription = "SiteSubscription",
SiteSupvisdSetting = "SiteSupvisdSetting",
SiteVMSDetails = "SiteVMSDetails",
StripePaymentMethod = "StripePaymentMethod",
StripePayoutDetails = "StripePayoutDetails",
SubscriptionStripeDetail = "SubscriptionStripeDetail",
SupvisdEventRule = "SupvisdEventRule",
Tax = "Tax",
TaxType = "TaxType",
TaxesTaxType = "TaxesTaxType",
TrackTikActivity = "TrackTikActivity",
TrackTikDetails = "TrackTikDetails",
TrackTikIncident = "TrackTikIncident",
TrackTikTask = "TrackTikTask",
TransactionLineItem = "TransactionLineItem",
TransactionLineItemTax = "TransactionLineItemTax",
Trigger = "Trigger",
User = "User",
UserVMSDetails = "UserVMSDetails",
VMSDetails = "VMSDetails",
WalletTransfer = "WalletTransfer",
WebhookHealth = "WebhookHealth"
}
type ModelName = Model[keyof Model]["__typename"];
/**
* A sortable ID in the format "{model}_{reversedTimestamp}{random}".
*/
type NameIdString = `${Lowercase<Models>}_${string}` & {
__brand: "NameIdString";
};
/**
* A uuid v4 (ish)
*/
type UUIDString = `${string}-${string}-${string}-${string}-${string}`;
/**
* A sortable ID in the format "{model}_{reversedTimestamp}{random}".
*/
declare const nameIdStringRegex: RegExp;
/**
* A valid uuid v4
*/
declare const uuidStringRegex: RegExp;
/**
* Checks if the value is a valid uuid v4
* @param value A uuid string hopefully
* @returns true or false
*/
declare function isUUID(value: unknown): value is UUIDString;
/**
* Checks if the value is a String
* @param value A string hopefully
* @returns true or false
*/
declare function isString(value: unknown): boolean;
/**
* Checks if the value is a NameID (a sortable ID in the format "{model}_{reversedTimestamp}{random}")
* @param value A valid NameID string hopefully
* @returns true or false
*/
declare function isNameId(value: unknown): value is NameIdString;
/**
* Checks if the value, or value['id'], is a valid uuid v4
* @param value A string or object with an 'id' property
* @returns true or false
* @example
* isHasUUID("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") // true
* isHasUUID({"id":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}) // true
*/
declare function isHasUUID(value: unknown): boolean;
/**
* Checks if the value is a known name for a Model
* @param value
* @returns true or false
*/
declare function isModelName(value: unknown | ModelName): value is ModelName;
/**
* Extracts the Model Name from a NameID
* @param nameId A string in the format "{model}_{reversedTimestamp}{random}"
* @returns A ModelName
* @example
* extractModelFromNameId('user_012345234567abcdefghijklmnopqrstuv') // returns 'User'
*/
declare function extractModelFromNameId(nameId: NameIdString): ModelName;
/**
* Extracts the Model Name from a NameID with a novel (unknown) model prefix
* @param nameId A string in the format "{model}_{reversedTimestamp}{random}"
* @returns A ModelName
* @example
* extractModelFromNameId('cat_012345234567abcdefghijklmnopqrstuv') // returns 'Cat'
*/
declare function extractModelFromNameIdSkipValidation(nameId: NameIdString): string;
/**
* Extracts the createdAt timestamp from a NameID
* @param nameId A string in the format "{model}_{reversedTimestamp}{random}"
* @param offset Optionally you can include an offset if a custom offset was used
* @returns a Date
*/
declare function extractTimestampFromNameId(nameId: NameIdString, offset?: number): Date;
/**
* Create a new Model Object with a valid NameID from an existing Model Object or a Model Name
*/
declare abstract class MutableModel {
id: UUIDString | NameIdString;
nameId: NameIdString;
createdAt: string;
updatedAt: string;
get __typename(): ModelName;
/**
* @param init An existing Model Object, or a Model Name
*/
constructor(init: Partial<Model[keyof Model]> | ModelName);
}
/**
* Represents a sortable ID.
*
* This class encapsulates the generation, validation, and manipulation of sortable IDs,
* which are used as primary keys in our database, particularly for time-series data.
*/
declare class NameID {
private _lexicographicBase32;
private _randomLength;
private _offset;
private _value;
/**
* @param { ModelName | Model | NameId } input - Can be a ModelName, a Model object (with __typename and createdAt), or a valid nameId string.
* @param { string | number | Date } time - Defaults to now.
* @param {boolean} skip - Skip 'Is Valid Model Name' check.
* @throws { Error } - Throws an error if the input is invalid.
*
* @example
* const NameID_For_Model = new NameID("User");
* const NameID_From_Model = new NameID({ __typename: "User", ...});
* const NameID_From_Model_With_UUID = new NameID({id: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", __typename: "User", ... });
*/
constructor(input: Model[ModelName] | ModelName | NameIdString, time?: string | number | Date, skip?: boolean);
/**
* Returns The string representation of the NameID.
* @example
* const nameId = new NameID("User");
* console.log(nameId.toString()); // Output: user_012345234567abcdefghijklmnopqrstuv
*/
get value(): NameIdString;
/**
* Convert a legacy object with a uuid id to a NameIdString
* @param object Any valid Model object
* @returns
*/
private fromUUID;
/**
* Generates a sortable ID with model prefix and reversed timestamp.
*
* This function creates a unique identifier suitable for use as a primary key
* in a database, particularly for time-series data or event-driven systems.
* It combines a model identifier, a reversed timestamp for reverse chronological
* sorting, and a random component for uniqueness.
*
* @param name - The model type name (e.g., "User").
* @param time - The timestamp to encode. If not provided, the current time is used.
*
* @returns The generated sortable ID in the format "{model}_{reversedTimestamp}{random}".
*
* @example
* const userId = generateNameID("User");
* const cameraEventId = generateNameID("CameraEvent", new Date("2024-08-15T12:30:00Z"));
*/
private generateNameID;
private generateEncodedTimestamp;
/**
* Checks if a given ID is valid based on the expected format.
*
* This function validates if a string conforms to the expected sortable ID
* format: "model_reversedTimestamp_random".
* @returns {boolean} - True if the ID is valid, false otherwise.
*
* @example
* const validId = generateNameID("user");
* const invalidId = "user-12345-abcde";
*
* console.log(isValidId(validId)); // true
* console.log(isValidId(invalidId)); // false
*/
get isValid(): boolean;
/**
* Decodes the timestamp from a NameID.
*
* @returns {Date | null} - The decoded timestamp as a Date object, or null if the ID is invalid.
*
* @example
* const { timestamp } = new NameID("event_abcdefghi");
* console.log(timestamp.toISOString());
*/
get timestamp(): Date | null;
/**
* Generates a sortable ID with model prefix and reversed timestamp.
*
* This function creates a unique identifier suitable for use as a primary key
* in a database, particularly for time-series data or event-driven systems.
* It combines a model identifier, a reversed timestamp for reverse chronological
* sorting, and a random component for uniqueness.
*
* @param value - Can be a ModelName, a Model object (with __typename and createdAt), or a valid nameId string.
* @param time - The timestamp to encode. If not provided, the current time is used.
*
* @returns The generated sortable ID in the format "model_{reversedTimestamp}{random}".
*
* @example
* const userId = generateNameID("User");
* const cameraEventId = generateNameID("CameraEvent", new Date("2024-08-15T12:30:00Z"));
*/
static from(value: unknown, time?: string | number | Date): NameID;
/**
* Checks if the input is a value nameId
* @param value A nameId.
* @param skip Skip 'Is Valid Model Name' check.
* @returns A model name and timestamp
*/
static parse(value: string, skip?: boolean): {
name: ModelName | string;
timestamp: Date;
};
}
/**
* Classes
*/
export { NameID, MutableModel };
/**
* Regexp
*/
export { uuidStringRegex, nameIdStringRegex };
/**
* Utilities
*/
export { isUUID, isString, isNameId, isHasUUID, isModelName, extractModelFromNameId, extractTimestampFromNameId, extractModelFromNameIdSkipValidation, };
/**
* Types
*/
export type { Models, ModelName, UUIDString, NameIdString };
export default NameID;
//# sourceMappingURL=name-id.d.ts.map