client.ts 955 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { BuildConfig, getBuildConfig } from "./build";
  2. export function getClientConfig() {
  3. if (typeof document !== "undefined") {
  4. // client side
  5. return JSON.parse(queryMeta("config")) as BuildConfig;
  6. }
  7. if (typeof process !== "undefined") {
  8. // server side
  9. return getBuildConfig();
  10. }
  11. }
  12. /**
  13. * 适配basePath不为空的情况
  14. * @param api
  15. */
  16. export function getFullApi(api: string) {
  17. const base = getClientConfig()?.baseApi ?? "";
  18. if (api.startsWith("/") && base.endsWith("/")) {
  19. return base + api.substring(1);
  20. }
  21. if (api.startsWith("/") || base.endsWith("/")) {
  22. return base + api;
  23. }
  24. return base + "/" + api;
  25. }
  26. function queryMeta(key: string, defaultValue?: string): string {
  27. let ret: string;
  28. if (document) {
  29. const meta = document.head.querySelector(
  30. `meta[name='${key}']`,
  31. ) as HTMLMetaElement;
  32. ret = meta?.content ?? "";
  33. } else {
  34. ret = defaultValue ?? "";
  35. }
  36. return ret;
  37. }