assert.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. 'use strict'
  2. const OError = require('@overleaf/o-error')
  3. const check = require('check-types')
  4. const { Blob } = require('overleaf-editor-core')
  5. const assert = check.assert
  6. const MONGO_ID_REGEXP = /^[0-9a-f]{24}$/
  7. const POSTGRES_ID_REGEXP = /^[1-9][0-9]{0,9}$/
  8. const MONGO_OR_POSTGRES_ID_REGEXP = /^([0-9a-f]{24}|[1-9][0-9]{0,9})$/
  9. function transaction(transaction, message) {
  10. assert.function(transaction, message)
  11. }
  12. function blobHash(arg, message) {
  13. try {
  14. assert.match(arg, Blob.HEX_HASH_RX, message)
  15. } catch (error) {
  16. throw OError.tag(error, message, { arg })
  17. }
  18. }
  19. /**
  20. * A project id is a string that contains either an integer (for projects stored in Postgres) or 24
  21. * hex digits (for projects stored in Mongo)
  22. */
  23. function projectId(arg, message) {
  24. try {
  25. assert.match(arg, MONGO_OR_POSTGRES_ID_REGEXP, message)
  26. } catch (error) {
  27. throw OError.tag(error, message, { arg })
  28. }
  29. }
  30. /**
  31. * A chunk id is a string that contains either an integer (for projects stored in Postgres) or 24
  32. * hex digits (for projects stored in Mongo)
  33. */
  34. function chunkId(arg, message) {
  35. try {
  36. assert.match(arg, MONGO_OR_POSTGRES_ID_REGEXP, message)
  37. } catch (error) {
  38. throw OError.tag(error, message, { arg })
  39. }
  40. }
  41. function mongoId(arg, message) {
  42. try {
  43. assert.match(arg, MONGO_ID_REGEXP, message)
  44. } catch (error) {
  45. throw OError.tag(error, message, { arg })
  46. }
  47. }
  48. function postgresId(arg, message) {
  49. try {
  50. assert.match(arg, POSTGRES_ID_REGEXP, message)
  51. } catch (error) {
  52. throw OError.tag(error, message, { arg })
  53. }
  54. }
  55. module.exports = {
  56. ...assert,
  57. transaction,
  58. blobHash,
  59. projectId,
  60. chunkId,
  61. mongoId,
  62. postgresId,
  63. MONGO_ID_REGEXP,
  64. POSTGRES_ID_REGEXP,
  65. }