2017-06-28 03:59:53 +00:00
|
|
|
// @flow
|
|
|
|
import { observable, action, runInAction } from 'mobx';
|
|
|
|
import { client } from 'utils/ApiClient';
|
|
|
|
import _ from 'lodash';
|
|
|
|
import invariant from 'invariant';
|
|
|
|
|
|
|
|
import stores from 'stores';
|
|
|
|
import Document from 'models/Document';
|
|
|
|
import ErrorsStore from 'stores/ErrorsStore';
|
|
|
|
|
|
|
|
class DocumentsStore {
|
|
|
|
@observable data: Object = {};
|
|
|
|
@observable isLoaded: boolean = false;
|
|
|
|
errors: ErrorsStore;
|
|
|
|
|
|
|
|
/* Actions */
|
|
|
|
|
2017-06-28 04:20:09 +00:00
|
|
|
@action fetchAll = async (request?: string = 'list'): Promise<*> => {
|
2017-06-28 03:59:53 +00:00
|
|
|
try {
|
2017-06-28 04:20:09 +00:00
|
|
|
const res = await client.post(`/documents.${request}`);
|
2017-06-28 03:59:53 +00:00
|
|
|
invariant(res && res.data, 'Document list not available');
|
|
|
|
const { data } = res;
|
|
|
|
runInAction('DocumentsStore#fetchAll', () => {
|
|
|
|
const loaded = _.keyBy(
|
|
|
|
data.map(document => new Document(document)),
|
|
|
|
'id'
|
|
|
|
);
|
|
|
|
this.data = {
|
|
|
|
...this.data,
|
|
|
|
...loaded,
|
|
|
|
};
|
|
|
|
this.isLoaded = true;
|
|
|
|
});
|
2017-06-28 04:20:09 +00:00
|
|
|
return data;
|
2017-06-28 03:59:53 +00:00
|
|
|
} catch (e) {
|
|
|
|
this.errors.add('Failed to load documents');
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2017-06-28 04:20:09 +00:00
|
|
|
@action fetchRecent = async (): Promise<*> => {
|
|
|
|
const data = await this.fetchAll('recent');
|
|
|
|
console.log(data);
|
|
|
|
};
|
|
|
|
|
|
|
|
@action fetchViewed = async (): Promise<*> => {
|
|
|
|
const data = await this.fetchAll('viewed');
|
|
|
|
console.log(data);
|
|
|
|
};
|
|
|
|
|
2017-06-28 03:59:53 +00:00
|
|
|
@action fetch = async (id: string): Promise<*> => {
|
|
|
|
try {
|
|
|
|
const res = await client.post('/documents.info', { id });
|
|
|
|
invariant(res && res.data, 'Document not available');
|
|
|
|
const { data } = res;
|
|
|
|
runInAction('DocumentsStore#fetch', () => {
|
2017-06-28 04:20:09 +00:00
|
|
|
this.add(new Document(data));
|
2017-06-28 03:59:53 +00:00
|
|
|
this.isLoaded = true;
|
|
|
|
});
|
|
|
|
} catch (e) {
|
|
|
|
this.errors.add('Failed to load documents');
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
@action add = (document: Document): void => {
|
|
|
|
this.data[document.id] = document;
|
|
|
|
};
|
|
|
|
|
|
|
|
@action remove = (id: string): void => {
|
|
|
|
delete this.data[id];
|
|
|
|
};
|
|
|
|
|
|
|
|
getById = (id: string): Document => {
|
|
|
|
return _.find(this.data, { id });
|
|
|
|
};
|
|
|
|
|
2017-06-28 04:20:09 +00:00
|
|
|
constructor() {
|
2017-06-28 03:59:53 +00:00
|
|
|
this.errors = stores.errors;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default DocumentsStore;
|