definma-ui/src/app/services/data.service.ts

53 lines
2.1 KiB
TypeScript

import { Injectable } from '@angular/core';
import {TemplateModel} from '../models/template.model';
import {ApiService} from './api.service';
import {MaterialModel} from '../models/material.model';
import {BaseModel} from '../models/base.model';
import {UserModel} from '../models/user.model';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(
private api: ApiService
) { }
private collectionMap = {
materials: {path: '/materials?status=all', model: MaterialModel, array: true},
materialSuppliers: {path: '/material/suppliers', model: null, array: true},
materialGroups: {path: '/material/groups', model: null, array: true},
materialTemplates: {path: '/template/materials', model: TemplateModel, array: true},
measurementTemplates: {path: '/template/measurements', model: TemplateModel, array: true},
conditionTemplates: {path: '/template/conditions', model: TemplateModel, array: true},
sampleNotesFields: {path: '/sample/notes/fields', model: TemplateModel, array: true},
users: {path: '/users', model: UserModel, array: true},
user: {path: '/user', model: UserModel, array: false},
userKey: {path: '/user/key', model: BaseModel, array: false}
};
arr: {[key: string]: any[]} = {}; // array of data
id: {[key: string]: {[id: string]: any}} = {}; // data in format _id: data
d: {[key: string]: any} = {}; // data not in array format
load(collection, f = () => {}) { // load data
if (this.arr[collection]) { // data already loaded
f();
}
else { // load data
this.api.get<any>(this.collectionMap[collection].path, data => {
if (this.collectionMap[collection].array) { // array data
this.arr[collection] = data
.map(e => this.collectionMap[collection].model ? new this.collectionMap[collection].model().deserialize(e) : e);
this.id[collection] = this.arr[collection].reduce((s, e) => {s[e._id] = e; return s; }, {});
}
else { // not array data
this.d[collection] = new this.collectionMap[collection].model().deserialize(data);
}
f();
});
}
}
}