update.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { create } from "zustand";
  2. import { persist } from "zustand/middleware";
  3. import { FETCH_COMMIT_URL, FETCH_TAG_URL } from "../constant";
  4. import { getCurrentVersion } from "../utils";
  5. export interface UpdateStore {
  6. lastUpdate: number;
  7. remoteId: string;
  8. getLatestCommitId: (force: boolean) => Promise<string>;
  9. }
  10. export const UPDATE_KEY = "chat-update";
  11. export const useUpdateStore = create<UpdateStore>()(
  12. persist(
  13. (set, get) => ({
  14. lastUpdate: 0,
  15. remoteId: "",
  16. async getLatestCommitId(force = false) {
  17. const overTenMins = Date.now() - get().lastUpdate > 10 * 60 * 1000;
  18. const shouldFetch = force || overTenMins;
  19. if (!shouldFetch) {
  20. return getCurrentVersion();
  21. }
  22. try {
  23. const data = await (await fetch(FETCH_TAG_URL)).json();
  24. const remoteId = data[0].name as string;
  25. set(() => ({
  26. lastUpdate: Date.now(),
  27. remoteId,
  28. }));
  29. console.log("[Got Upstream] ", remoteId);
  30. return remoteId;
  31. } catch (error) {
  32. console.error("[Fetch Upstream Commit Id]", error);
  33. return getCurrentVersion();
  34. }
  35. },
  36. }),
  37. {
  38. name: UPDATE_KEY,
  39. version: 1,
  40. },
  41. ),
  42. );