Source: services/route-builder.js

  1. /**
  2. * Common functions and utilities for tasks related to route building
  3. *
  4. * @module
  5. */
  6. import toArray from '../core/base-service/to-array.js'
  7. /*
  8. * Factory class for building a BaseService `route` object. This class is useful
  9. * in complex collections of service classes, when the URL is built
  10. * conditionally.
  11. *
  12. * Patterns based on path-to-regex may obviate the need for this, though they
  13. * haven't done so yet.
  14. */
  15. export default class RouteBuilder {
  16. /**
  17. * Creates a RouteBuilder object.
  18. *
  19. * @param {object} attrs - Refer to individual attributes
  20. * @param {string} attrs.base - Base URL, defaults to ''
  21. */
  22. constructor({ base = '' } = {}) {
  23. this.base = base
  24. this._formatComponents = []
  25. this.capture = []
  26. }
  27. /**
  28. * Get the format components separated by '/'
  29. *
  30. * @returns {string} Format components, for example: "format1/format2/format3"
  31. */
  32. get format() {
  33. return this._formatComponents.join('/')
  34. }
  35. /**
  36. * Saves the format and capture values in the RouteBuilder instance.
  37. *
  38. * @param {string} format - Pattern based on path-to-regex, for example: (?:(.+)\\.)?${serviceBaseUrl}
  39. * @param {string} capture - Value to capture
  40. * @returns {object} RouteBuilder instance for chaining
  41. */
  42. push(format, capture) {
  43. this._formatComponents = this._formatComponents.concat(toArray(format))
  44. this.capture = this.capture.concat(toArray(capture))
  45. // Return `this` for chaining.
  46. return this
  47. }
  48. /**
  49. * Returns a new object based on RouteBuilder instance containing its base, format and capture properties.
  50. *
  51. * @returns {object} Object containing base, format and capture properties of the RouteBuilder instance
  52. */
  53. toObject() {
  54. const { base, format, capture } = this
  55. return { base, format, capture }
  56. }
  57. }