update.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. const data = await (await fetch(FETCH_COMMIT_URL)).json();
  26. const remoteId = (data[0].sha as string).substring(0, 7);
  27. set(() => ({
  28. lastUpdate: Date.now(),
  29. remoteId,
  30. }));
  31. console.log("[Got Upstream] ", remoteId);
  32. return remoteId;
  33. } catch (error) {
  34. console.error("[Fetch Upstream Commit Id]", error);
  35. return getCurrentVersion();
  36. }
  37. },
  38. }),
  39. {
  40. name: UPDATE_KEY,
  41. version: 1,
  42. },
  43. ),
  44. );