UNPKG

@fakel/rest-admin

Version:

An application that makes it easier to work with your API

131 lines (103 loc) 3.25 kB
import { observable, action, makeObservable } from 'mobx'; import type { DataProviderT } from '../@types/dataProvider'; type GetDataOptions = { withReferences?: boolean; reference?: string[]; }; export class ListStore { dataSource: Array<any> = []; ids: number[] = []; total: number = 0; loading: boolean = false; references: any[]; constructor() { makeObservable(this, { dataSource: observable, ids: observable, total: observable, loading: observable, }); } public deleteSelectedRecords(ids: any[]) { this.dataSource = this.dataSource.filter((record) => { return !ids.includes(record.id); }); } public async deleteRecords(dataProvider: DataProviderT, resource: string, ids: any[]) { this.deleteSelectedRecords(ids); await dataProvider.delete(resource, { id: ids, }); this.dataSource = this.dataSource.filter((record) => !ids.includes(record.id)); } public async getReferencesData(dataProvider: DataProviderT, resource: string) { this.setLoading(true); const { data: records } = await dataProvider.getList(resource, { ids: this.ids }); if (!records) { this.setReferenceData([]); return; } const recordsWitId = records.map((record, index) => ({ ...record, id: record.id || index })); this.setReferenceData([...this.references, { [resource]: recordsWitId }]); } public getReference(name: string) { return this.references ? this.references[name] : []; } public getReferenceById(reference: string, id: number) { return this.getReference(reference).find((refItem) => refItem.id === id); } public getReferenceByQuery(reference: string, query: string, value: any) { return this.getReference(reference).find((refItem) => refItem[query] === value); } public async getData( dataProvider: DataProviderT, resource: string, params: any = {}, options: GetDataOptions = {}, ) { try { this.setLoading(true); const { data: records, total } = await dataProvider.getList(resource, params); if (!records) { this.setDataSource([]); this.setDataSourceIds([]); this.setTotal(0); this.setLoading(false); return; } const ids = records.map((_, index) => index); const dataWithKey = records.map((dataItem, index) => ({ ...dataItem, key: dataItem.id || index, })); this.setDataSource(dataWithKey); this.setDataSourceIds(ids); this.setTotal(total); this.setLoading(false); if (options && options.withReferences) { options.reference.forEach((reference) => this.getReferencesData(dataProvider, reference)); } } catch (error) { if (dataProvider.checkError) { await dataProvider.checkError(error); } else { throw new Error(error); } } } public setLoading(loading: boolean) { this.loading = loading; } public setReferenceData = (data) => { this.references = data; }; public setDataSource = (data) => { this.dataSource = data; }; public setTotal = (value) => { this.total = value; }; public setDataSourceIds = (value) => { this.ids = value; }; }