index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*!
  2. * uid-safe
  3. * Copyright(c) 2014 Jonathan Ong
  4. * Copyright(c) 2015-2016 Douglas Christopher Wilson
  5. * MIT Licensed
  6. */
  7. 'use strict'
  8. /**
  9. * Module dependencies.
  10. * @private
  11. */
  12. var escape = require('base64-url').escape
  13. var randomBytes = require('random-bytes')
  14. /**
  15. * Module exports.
  16. * @public
  17. */
  18. module.exports = uid
  19. module.exports.sync = uidSync
  20. /**
  21. * Create a unique ID.
  22. *
  23. * @param {number} length
  24. * @param {function} [callback]
  25. * @return {Promise}
  26. * @public
  27. */
  28. function uid (length, callback) {
  29. // validate callback is a function, if provided
  30. if (callback !== undefined && typeof callback !== 'function') {
  31. throw new TypeError('argument callback must be a function')
  32. }
  33. // require the callback without promises
  34. if (!callback && !global.Promise) {
  35. throw new TypeError('argument callback is required')
  36. }
  37. if (callback) {
  38. // classic callback style
  39. return generateUid(length, callback)
  40. }
  41. return new Promise(function executor (resolve, reject) {
  42. generateUid(length, function onUid (err, str) {
  43. if (err) return reject(err)
  44. resolve(str)
  45. })
  46. })
  47. }
  48. /**
  49. * Create a unique ID sync.
  50. *
  51. * @param {number} length
  52. * @return {string}
  53. * @public
  54. */
  55. function uidSync (length) {
  56. return toString(randomBytes.sync(length))
  57. }
  58. /**
  59. * Generate a unique ID string.
  60. *
  61. * @param {number} length
  62. * @param {function} callback
  63. * @private
  64. */
  65. function generateUid (length, callback) {
  66. randomBytes(length, function (err, buf) {
  67. if (err) return callback(err)
  68. callback(null, toString(buf))
  69. })
  70. }
  71. /**
  72. * Change a Buffer into a string.
  73. *
  74. * @param {Buffer} buf
  75. * @return {string}
  76. * @private
  77. */
  78. function toString (buf) {
  79. return escape(buf.toString('base64'))
  80. }