UNPKG

2.81 kBJavaScriptView Raw
1'use strict';
2
3var alphabet = require('./alphabet');
4var encode = require('./encode');
5var decode = require('./decode');
6var isValid = require('./is-valid');
7
8// Ignore all milliseconds before a certain time to reduce the size of the date entropy without sacrificing uniqueness.
9// This number should be updated every year or so to keep the generated id short.
10// To regenerate `new Date() - 0` and bump the version. Always bump the version!
11var REDUCE_TIME = 1459707606518;
12
13// don't change unless we change the algos or REDUCE_TIME
14// must be an integer and less than 16
15var version = 6;
16
17// if you are using cluster or multiple servers use this to make each instance
18// has a unique value for worker
19// Note: I don't know if this is automatically set when using third
20// party cluster solutions such as pm2.
21var clusterWorkerId = require('./util/cluster-worker-id') || 0;
22
23// Counter is used when shortid is called multiple times in one second.
24var counter;
25
26// Remember the last time shortid was called in case counter is needed.
27var previousSeconds;
28
29/**
30 * Generate unique id
31 * Returns string id
32 */
33function generate() {
34
35 var str = '';
36
37 var seconds = Math.floor((Date.now() - REDUCE_TIME) * 0.001);
38
39 if (seconds === previousSeconds) {
40 counter++;
41 } else {
42 counter = 0;
43 previousSeconds = seconds;
44 }
45
46 str = str + encode(alphabet.lookup, version);
47 str = str + encode(alphabet.lookup, clusterWorkerId);
48 if (counter > 0) {
49 str = str + encode(alphabet.lookup, counter);
50 }
51 str = str + encode(alphabet.lookup, seconds);
52
53 return str;
54}
55
56
57/**
58 * Set the seed.
59 * Highly recommended if you don't want people to try to figure out your id schema.
60 * exposed as shortid.seed(int)
61 * @param seed Integer value to seed the random alphabet. ALWAYS USE THE SAME SEED or you might get overlaps.
62 */
63function seed(seedValue) {
64 alphabet.seed(seedValue);
65 return module.exports;
66}
67
68/**
69 * Set the cluster worker or machine id
70 * exposed as shortid.worker(int)
71 * @param workerId worker must be positive integer. Number less than 16 is recommended.
72 * returns shortid module so it can be chained.
73 */
74function worker(workerId) {
75 clusterWorkerId = workerId;
76 return module.exports;
77}
78
79/**
80 *
81 * sets new characters to use in the alphabet
82 * returns the shuffled alphabet
83 */
84function characters(newCharacters) {
85 if (newCharacters !== undefined) {
86 alphabet.characters(newCharacters);
87 }
88
89 return alphabet.shuffled();
90}
91
92
93// Export all other functions as properties of the generate function
94module.exports = generate;
95module.exports.generate = generate;
96module.exports.seed = seed;
97module.exports.worker = worker;
98module.exports.characters = characters;
99module.exports.decode = decode;
100module.exports.isValid = isValid;