Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

73 lignes
2.1 KiB

  1. import {logger} from '../../service/logging/global.ts'
  2. export type RouteParameters = { [key: string]: string }
  3. export type RouteSegment = { base: string, match: string | undefined }
  4. export type ZippedRouteSegments = RouteSegment[]
  5. /**
  6. * Abstract base class representing a parsed and loaded route.
  7. */
  8. export abstract class Route {
  9. constructor(
  10. /**
  11. * The base definition string.
  12. * @type string
  13. */
  14. protected base: string
  15. ) { }
  16. /**
  17. * Given an incoming route path, returns true if that route matches this route definition.
  18. * @param {string} incoming
  19. * @return boolean
  20. */
  21. public abstract match(incoming: string): boolean
  22. /**
  23. * Given an incoming route path, parse the parameters and return them.
  24. * @param {string} incoming
  25. * @return RouteParameters
  26. */
  27. public abstract build_parameters(incoming: string): RouteParameters
  28. /**
  29. * Get the base definition of this route.
  30. */
  31. public get route() {
  32. return this.base
  33. }
  34. /**
  35. * Split the given route string into its segments by '/'.
  36. * @param {string} incoming
  37. * @return {Array<string>}
  38. */
  39. public split(incoming: string) {
  40. return incoming.toLowerCase().split('/')
  41. }
  42. /**
  43. * Split the incoming route segment and match each segment with the corresponding segment of the definition.
  44. * @param {string} incoming
  45. * @return ZippedRouteSegments
  46. */
  47. public zip(incoming: string) {
  48. const incoming_parts: string[] = this.split(incoming)
  49. const base_parts: string[] = this.split(this.base)
  50. const zipped_parts: ZippedRouteSegments = []
  51. if ( incoming_parts.length !== base_parts.length ) {
  52. logger.warn(`Zipping routes with different part lengths! (Base: ${this.base}, Incoming: ${incoming}`)
  53. }
  54. base_parts.forEach((part, index) => {
  55. zipped_parts.push({
  56. base: part,
  57. match: (index >= incoming_parts.length ? undefined : incoming_parts[index]),
  58. })
  59. })
  60. return zipped_parts
  61. }
  62. }