utils.gen.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. // This file is auto-generated by @hey-api/openapi-ts
  2. import type { QuerySerializer } from "./bodySerializer.gen.js"
  3. import {
  4. type ArraySeparatorStyle,
  5. serializeArrayParam,
  6. serializeObjectParam,
  7. serializePrimitiveParam,
  8. } from "./pathSerializer.gen.js"
  9. export interface PathSerializer {
  10. path: Record<string, unknown>
  11. url: string
  12. }
  13. export const PATH_PARAM_RE = /\{[^{}]+\}/g
  14. export const defaultPathSerializer = ({ path, url: _url }: PathSerializer) => {
  15. let url = _url
  16. const matches = _url.match(PATH_PARAM_RE)
  17. if (matches) {
  18. for (const match of matches) {
  19. let explode = false
  20. let name = match.substring(1, match.length - 1)
  21. let style: ArraySeparatorStyle = "simple"
  22. if (name.endsWith("*")) {
  23. explode = true
  24. name = name.substring(0, name.length - 1)
  25. }
  26. if (name.startsWith(".")) {
  27. name = name.substring(1)
  28. style = "label"
  29. } else if (name.startsWith(";")) {
  30. name = name.substring(1)
  31. style = "matrix"
  32. }
  33. const value = path[name]
  34. if (value === undefined || value === null) {
  35. continue
  36. }
  37. if (Array.isArray(value)) {
  38. url = url.replace(match, serializeArrayParam({ explode, name, style, value }))
  39. continue
  40. }
  41. if (typeof value === "object") {
  42. url = url.replace(
  43. match,
  44. serializeObjectParam({
  45. explode,
  46. name,
  47. style,
  48. value: value as Record<string, unknown>,
  49. valueOnly: true,
  50. }),
  51. )
  52. continue
  53. }
  54. if (style === "matrix") {
  55. url = url.replace(
  56. match,
  57. `;${serializePrimitiveParam({
  58. name,
  59. value: value as string,
  60. })}`,
  61. )
  62. continue
  63. }
  64. const replaceValue = encodeURIComponent(style === "label" ? `.${value as string}` : (value as string))
  65. url = url.replace(match, replaceValue)
  66. }
  67. }
  68. return url
  69. }
  70. export const getUrl = ({
  71. baseUrl,
  72. path,
  73. query,
  74. querySerializer,
  75. url: _url,
  76. }: {
  77. baseUrl?: string
  78. path?: Record<string, unknown>
  79. query?: Record<string, unknown>
  80. querySerializer: QuerySerializer
  81. url: string
  82. }) => {
  83. const pathUrl = _url.startsWith("/") ? _url : `/${_url}`
  84. let url = (baseUrl ?? "") + pathUrl
  85. if (path) {
  86. url = defaultPathSerializer({ path, url })
  87. }
  88. let search = query ? querySerializer(query) : ""
  89. if (search.startsWith("?")) {
  90. search = search.substring(1)
  91. }
  92. if (search) {
  93. url += `?${search}`
  94. }
  95. return url
  96. }