Comment

Comment by strnisa

I've become a fan of unique, relatively short and "human-readable" IDs, such at the ones used by Stripe, e.g. `cus_MJA953cFzEuO1z` for an ID of a customer. Here's a Stripe dev article on the topic: https://dev.to/stripe/designing-apis-for-humans-object-ids-3...

If you use JavaScript/TypeScript, you can make them like this:

    function makeSlug(length: number): string {
        const validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        const randomBytes = crypto.randomBytes(length);
        let result = "";
        for (let i = 0; i < length; i++) {
            result += validChars[randomBytes[i] % validChars.length];
        }
        return result;
    }

    function makeId(tableName: string): string {
        const idSpec = TABLE_NAME_TO_ID_SPEC[tableName];
        const prefix = idSpec.prefix;
        const slugLength = idSpec.length - prefix.length - 1;
        return `${prefix}_${makeSlug(slugLength)}`;
    }
parent strnisa 2 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton