Skip to content

Instantly share code, notes, and snippets.

@wcoder
Created February 23, 2021 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wcoder/01487275e04faaca54051a17be6ccd11 to your computer and use it in GitHub Desktop.
Save wcoder/01487275e04faaca54051a17be6ccd11 to your computer and use it in GitHub Desktop.
Snippet to simply generate Firestore Document ID outside of Firebase SDK. (Javascript, Node.js)
const { randomBytes } = require('crypto');
// Sources: https://github.com/firebase/firebase-js-sdk/blob/4090271bb71023c3e6587d8bd8315ebf99b3ccd7/packages/firestore/src/util/misc.ts#L27-L55
const newId = () => {
// Alphanumeric characters
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
// The largest byte value that is a multiple of `char.length`.
const maxMultiple = Math.floor(256 / chars.length) * chars.length;
let autoId = '';
const targetLength = 20;
while (autoId.length < targetLength) {
const bytes = randomBytes(40);
for (let i = 0; i < bytes.length; ++i) {
// Only accept values that are [0, maxMultiple), this ensures they can
// be evenly mapped to indices of `chars` via a modulo operation.
if (autoId.length < targetLength && bytes[i] < maxMultiple) {
autoId += chars.charAt(bytes[i] % chars.length);
}
}
}
return autoId;
}
// Usage:
// newId() => 7MShqEngbz1ZgCk6U0zA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment