-
Notifications
You must be signed in to change notification settings - Fork 14
/
api.js
91 lines (74 loc) · 2.25 KB
/
api.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import path from 'path';
import os from 'os';
import fs from 'fs';
import {IndexedTable,Table} from './table.js';
const State = {
root: null
};
export function config({root:root = os.homedir()} = {}) {
State.root = path.resolve(root);
if ( ! fs.existsSync(State.root) ) {
fs.mkdirSync(State.root, {recursive:true});
}
}
export function getTable(name) {
guardSetup();
let tableBase = path.resolve(State.root, name, "tableInfo.json");
let tableInfo;
if ( ! fs.existsSync(tableBase) ) {
fs.mkdirSync(path.dirname(tableBase), {recursive:true});
}
try {
tableInfo = JSON.parse(fs.readFileSync(tableBase).toString());
} catch(e) {
tableInfo = {
tableBase,
name,
createdAt: Date.now()
};
fs.writeFileSync(tableBase, JSON.stringify(tableInfo,null,2));
}
return new Table(tableInfo);
}
export function getIndexedTable(name, indexed_properties = []) {
const table = getTable(name);
const {tableInfo} = table;
if ( ! tableInfo.indexes ) {
tableInfo.indexes = [];
}
const props = new Set([...tableInfo.indexes, ...indexed_properties]);
tableInfo.indexes = [...props.keys()].sort();
tableInfo.indexBase = {};
for( const prop of tableInfo.indexes ) {
const indexInfoBase = path.resolve(path.dirname(tableInfo.tableBase), '_indexes', prop, 'indexInfo.json');
if ( ! fs.existsSync(indexInfoBase) ) {
fs.mkdirSync(path.dirname(indexInfoBase), {recursive:true});
let indexInfo;
try {
indexInfo = JSON.parse(fs.readFileSync(indexInfoBase).toString());
} catch(e) {
indexInfo = {
property_name: prop,
createdAt: Date.now()
};
fs.writeFileSync(indexInfoBase, JSON.stringify(indexInfo,null,2));
}
}
tableInfo.indexBase[prop] = path.dirname(indexInfoBase);
}
return new IndexedTable(tableInfo);
}
export function rebuildIndexedTable(name, indexed_properties) {
console.log({name, indexed_properties});
throw new TypeError(`Not implemented`);
}
export function dropTable(name) {
guardSetup();
let tableBase = path.resolve(State.root, name);
fs.rmdirSync(tableBase, {recursive:true});
}
function guardSetup() {
if ( ! State.root ) {
throw new TypeError(`Please call config to set a base path first`);
}
}