Newer
Older
taehui / qwilight-fe / src / note / setNoteStore.ts
@Taehui Taehui on 13 Dec 1 KB v1.0.0
import { runInAction } from "mobx";
import { getMillis } from "taehui-ts/date";

import { GetNoteAPI, NoteAPINote } from "src/wwwAPI";
import { wwwAXIOS } from "src/Www";

export default function setNoteStore() {
  let lastMillis = getMillis();
  let lastWant = "";
  let lastSrc = 0;

  return {
    totalCount: 0,
    highestCount: 0,
    wantAvatar: "",
    notes: [] as NoteAPINote[],
    input: "",
    lastPage: 1,
    pageUnit: 10,
    viewUnit: 20,
    isLoading: false,

    setInput(input: string) {
      this.input = input;
    },

    async getNote(
      want: string,
      page: number,
      fit: number,
      src: number,
      setPage: (page: number) => void,
    ) {
      this.wantAvatar = src === 1 ? want : "";
      if ((want !== lastWant || src !== lastSrc) && page > 1) {
        setPage(1);
      } else {
        const millis = getMillis();
        lastMillis = millis;
        this.isLoading = true;
        const { status, data } = await wwwAXIOS.get<GetNoteAPI>("/note", {
          params: {
            fit,
            src,
            want,
            page,
            viewUnit: this.viewUnit,
          },
        });
        if (millis >= lastMillis) {
          if (status === 200) {
            runInAction(() => {
              this.totalCount = data.totalCount;
              this.highestCount = data.highestCount;
              this.lastPage = Math.max(
                1,
                Math.ceil(data.noteCount / this.viewUnit),
              );
              this.notes = data.notes;
              this.isLoading = false;
            });
          }
        }
      }
      lastWant = want;
      lastSrc = src;
    },
  };
}