Files
pupil.brain.riken.jp/src/components/database/lib/IndexUtil.ts
T

98 lines
2.3 KiB
TypeScript

import loki from 'lokijs';
import indexesJson from '../../../assets/tree.json';
export interface Index {
id: number;
title: string;
numOfItems: number;
parentId: number;
}
export const INDEX_ID_ROOT = 1;
export const INDEX_ID_PUBLIC = 3;
interface IndexJson {
id: number;
title: string;
num_of_items: number;
children: IndexJson[];
}
interface LokiColEntry {
key: number;
index: Index;
}
const lokiDB = new loki('database');
const lokiCol: Collection<any> = lokiDB.addCollection('indexes');
let lokiColKey: number = 0;
const store = (jsonArr: IndexJson[], parentId: number) => {
jsonArr.forEach((json: IndexJson) => {
const entry: LokiColEntry = {
key: ++lokiColKey,
index: {
id: json.id,
title: json.title,
numOfItems: json.num_of_items,
parentId: parentId,
},
};
lokiCol.insert(entry);
store(json.children, json.id)
});
}
store(indexesJson, INDEX_ID_ROOT);
class IndexUtil {
static getUrl(id: number): string {
return '/database/list/' + String(id);
}
static get(indexId: number): Index | null {
const filter = {
'index.id': indexId,
}
const res = lokiCol.findOne(filter);
if (res === null) {
return null;
}
return res.index as Index;
}
static getChildren(indexId: number): Index[] {
const filter = {
'index.parentId': indexId,
}
const res = lokiCol.chain().find(filter).simplesort('key').data();
return res.map((entry: LokiColEntry) => {
return entry.index;
});
}
static countChildren(indexId: number): number {
const filter = {
'index.parentId': indexId,
}
const res = lokiCol.count(filter);
return res;
}
static getParents(parentId: number): Index[] {
let parents: Index[] = [];
const loop = (parentId: number) => {
if (parentId !== INDEX_ID_ROOT) {
const parent = this.get(parentId);
if (parent !== null) {
loop(parent.parentId);
parents.push(parent);
}
}
}
loop(parentId);
return parents;
}
}
export default IndexUtil;