update.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { create } from "zustand";
  2. import { persist } from "zustand/middleware";
  3. import { FETCH_COMMIT_URL } from "../constant";
  4. import { getCurrentCommitId } 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 overOneHour = Date.now() - get().lastUpdate > 3600 * 1000;
  18. const shouldFetch = force || overOneHour;
  19. if (!shouldFetch) {
  20. return getCurrentCommitId();
  21. }
  22. try {
  23. const data = await (await fetch(FETCH_COMMIT_URL)).json();
  24. const sha = data[0].sha as string;
  25. const remoteId = sha.substring(0, 7);
  26. set(() => ({
  27. lastUpdate: Date.now(),
  28. remoteId,
  29. }));
  30. console.log("[Got Upstream] ", remoteId);
  31. return remoteId;
  32. } catch (error) {
  33. console.error("[Fetch Upstream Commit Id]", error);
  34. return getCurrentCommitId();
  35. }
  36. },
  37. }),
  38. {
  39. name: UPDATE_KEY,
  40. version: 1,
  41. }
  42. )
  43. );