import { makeAutoObservable } from "mobx"; import { accountInfo, coin_list, market_list, personal_nft } from "~/api"; import { StoreLocalStorageKey } from "~/types"; import { CoinList, MarketNFTData, UserInfo } from "~/types/store"; interface Store { state: object; } class AppStore implements Store { state = { token: "", walletAddress: "", coinList: [] as CoinList[], userInfo: {} as UserInfo, visibleUnLogin: false, likeNft: [] as MarketNFTData[], //喜歡的NFT myNft: [] as MarketNFTData[], //我的NFT auctionNft: [] as MarketNFTData[], //拍賣NFT sellNft: [] as MarketNFTData[], //售賣NFT issueNft: [] as MarketNFTData[], //發行搶購NFT rmdNft: [] as MarketNFTData[], //推薦NFT }; constructor() { makeAutoObservable(this); this.initState(); } /** * @description 初始化数据 */ initState() { let addr = window.localStorage.getItem(StoreLocalStorageKey.ADDRESS) || ""; let token = window.localStorage.getItem(StoreLocalStorageKey.TOKEN) || ""; this.state.walletAddress = addr; this.state.token = token; } /** * @description 设置token */ setToken(token: string): void { this.state.token = token; window.localStorage.setItem(StoreLocalStorageKey.TOKEN, token); } /** * @description 移除token */ removeToken(): void { this.state.token = ""; window.localStorage.removeItem(StoreLocalStorageKey.TOKEN); } async getUserInfo(): Promise { const res: any = await accountInfo(); if (res && res.code === 0) { this.state.userInfo = res.data; } return res && res.data; } resetUserInfo() { this.state.userInfo = {} as UserInfo; } /** * @description 设置地址 */ setAddress(addr: string): void { this.state.walletAddress = addr; window.localStorage.setItem(StoreLocalStorageKey.ADDRESS, addr); } /** * @description 移除地址 */ removeAddr(): void { this.state.walletAddress = ""; window.localStorage.removeItem(StoreLocalStorageKey.ADDRESS); } async getCoinList(): Promise { const res: any = await coin_list(); if (res && res.code === 0 && res.data) { this.state.coinList = res.data; } } resetCoinList(): void { this.state.coinList = []; } setVisibleUnLogin(bool: boolean): void { this.state.visibleUnLogin = bool; } /** * @param key * @param type 1.我的 2.喜歡的 */ async getMyNft(key: "myNft" | "likeNft") { let type = key === "myNft" ? 1 : 2; const res: any = await personal_nft(type); if (res && res.code === 0) { this.state[key] = res.data; } } resetNft(key: "myNft" | "likeNft") { this.state[key] = []; } async getMarketNft(key: "auctionNft" | "sellNft" | "rmdNft" | "issueNft") { const types = { auctionNft: 1, sellNft: 2, issueNft: 3, rmdNft: 4, }; const res: any = await market_list(types[key]); if (res && res.code === 0 && res.data) { this.state[key] = res.data; } } } const store = new AppStore(); export default store;