Created
February 23, 2021 12:00
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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