Newer
Older
taehui / qwilight-fe / src / note / setNoteStore.ts
@Taehui Taehui on 10 Nov 1 KB 2023-11-10 오후 7:03
import { runInAction } from "mobx";
import { getMillis } from "taehui-ts/date";

import { NoteAPINote, GetNoteAPI } 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[],
    noteVariety: 0,
    fit: 0,
    src: 0,
    input: "",
    want: "",
    lastPage: 0,
    pageUnit: 10,
    viewUnit: 20,
    isLoading: false,

    setNoteVariety(noteVariety: number) {
      this.noteVariety = noteVariety;
    },

    setFit(fit: number) {
      this.fit = fit;
    },

    setSrc(src: number) {
      this.src = src;
    },

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

    setWant(want: string) {
      this.want = want;
    },

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