-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
280 lines (252 loc) · 7.96 KB
/
index.ts
File metadata and controls
280 lines (252 loc) · 7.96 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import Vue, {VueConstructor} from 'vue';
import {
JsonServiceClient,
normalizeKey,
toDate, getField, splitOnFirst,
errorResponse, errorResponseExcept,
toPascalCase,
queryString, padInt, appendQueryString, humanize,
} from '@servicestack/client';
declare let global: any; // populated from package.json/jest
export const client = new JsonServiceClient('/');
import {desktopInfo, desktopTextFile, evaluateCode, desktopSaveTextFile} from '@servicestack/desktop';
import {Prop} from "vue-property-decorator";
export class RowComponent extends Vue {
@Prop() public db: string;
@Prop() public table: string;
@Prop() row: any;
@Prop() columns: ColumnSchema[];
}
const rowComponents:{[id:string]:{[id:string]:string}} = {};
export function getRowComponent(db:string, table:string) {
db = db.toLowerCase();
table = table.toLowerCase();
return rowComponents[db] && rowComponents[db][table] || null;
}
export function registerRowComponent<VC extends VueConstructor>(db:string, table:string, constructor:VC, component:string) {
Vue.component(component, constructor);
db = db.toLowerCase();
table = table.toLowerCase();
if (!rowComponents[db])
rowComponents[db] = {};
rowComponents[db][table] = component;
}
export enum Roles {
Admin = 'Admin',
}
export interface DesktopInfo {
tool:string;
toolVersion:string;
chromeVersion:string;
}
export interface ColumnSchema {
columnName: string;
columnOrdinal: number;
isUnique: boolean;
isKey: boolean;
isAutoIncrement: boolean;
isRowVersion: boolean;
isExpression: boolean;
dataType: string;
dataTypeName: string;
allowDBNull: boolean;
columnDefinition: string;
numericPrecision: number;
numericScale: number;
baseCatalogName: string;
baseColumnName: string;
baseSchemaName: string;
baseTableName: string;
}
// Shared state between all Components
interface State {
debug: boolean|null;
desktop: DesktopInfo|null;
hasExcel: boolean|null;
namedDbs: string[],
tables: {[id:string]:string[]};
totals: {[id:string]:{[id:string]:number}};
columns: {[id:string]:{[id:string]:ColumnSchema[]}};
getColumnTotal(db:string,table:string):number|null;
getColumnSchemas(db:string,table:string):ColumnSchema[];
dbConfigs: {[id:string]:DbConfig};
}
export const store: State = {
debug: global.CONFIG.debug as boolean,
desktop: global.CONFIG.desktop as DesktopInfo,
hasExcel: global.CONFIG.hasExcel as boolean,
namedDbs: global.CONFIG.namedDbs as string[],
tables: global.CONFIG.tables as {[id:string]:string[]},
totals: {},
columns: {},
getColumnTotal(db: string, table: string) {
const ret = this.totals[db] && this.totals[db][table];
return ret != null ? ret : null;
},
getColumnSchemas(db: string, table: string) {
return this.columns[db] && this.columns[db][table] || [];
},
dbConfigs: {},
};
interface DbConfig {
tableName?(name:string):string;
showTables?:string[];
links?:any;
rowComponents?:{[table:string]:VueConstructor};
}
export function dbConfig(db:string, config:DbConfig) {
if (db != 'main' && store.namedDbs.indexOf(db) < 0) return;
if (config.showTables && config.showTables.length > 0) {
Vue.set(store.tables, db, config.showTables);
}
if (config.rowComponents) {
for (let table of Object.keys(config.rowComponents)) {
registerRowComponent(db, table, config.rowComponents[table], table);
}
}
Vue.set(store.dbConfigs, db, config);
}
export const splitPascalCase = (table:string) =>
humanize(table).split(' ').map(toPascalCase).join(' ')
class EventBus extends Vue {
store = store;
}
export const bus = new EventBus({ data: store });
export interface DesktopSettings
{
[db:string]:{[table:string]:TableSettings};
}
export interface TableSettings
{
skip?:number;
orderBy?:string;
filters?:any;
fields?:string[];
}
let settings:DesktopSettings = {};
let settingsLoaded = false;
export async function loadSettings() {
try {
const settingsJson = store.desktop
? await desktopTextFile('settings.json')
: localStorage.getItem('settings.json');
if (settingsJson) {
settings = JSON.parse(settingsJson) as DesktopSettings || {};
log('loaded', settings);
bus.$emit('settings');
}
} catch (e) {
log(`Could not retrieve desktopTextFile 'settings.json'`, e);
} finally {
settingsLoaded = true;
}
}
export async function saveSettings() {
try {
//log('saveSettings', settings, store.desktop);
const settingsJson = JSON.stringify(settings);
if (store.desktop) {
await desktopSaveTextFile('settings.json', settingsJson);
} else {
localStorage.setItem('settings.json', settingsJson);
}
} catch (e) {
log(`Could not retrieve saveDesktopTextFile 'settings.json'`, e);
}
}
export function getTableSettings(db:string,table:string):TableSettings {
return settings[db] && settings[db][table] || null;
}
export async function saveTableSettings(db:string,table:string,tableSettings:TableSettings|null) {
if (!settingsLoaded) return;
if (!settings[db]) {
settings[db] = {};
}
if (tableSettings) {
settings[db][table] = tableSettings;
}
else {
delete settings[db][table];
}
await saveSettings();
}
export function log(...o:any[]) {
if (store.debug)
console.log.apply(console, arguments as any);
return o;
}
export const dateFmtHMS = (d: Date = new Date()) =>
`${d.getFullYear()-2000}${padInt(d.getMonth() + 1)}${padInt(d.getDate())}-${padInt(d.getHours())}${padInt(d.getMinutes())}${padInt(d.getSeconds())}`;
export async function openUrl(url:string) {
if (store.desktop) {
await evaluateCode(`openUrl('${url}')`);
} else {
window.open(url);
}
}
export async function exec(c:any, fn:() => Promise<any>) {
try {
c.loading = true;
c.responseStatus = null;
return await fn();
} catch (e) {
log(e);
c.responseStatus = e.responseStatus || (typeof e == 'string' ? { errorCode:'Error', message:e } : null) || e;
c.$emit('error', c.responseStatus);
} finally {
c.loading = false;
}
}
export async function loadTable(c:any, db:string,table:string) {
if (store.getColumnSchemas(db, table).length > 0) return;
await exec(c, async () => {
const r = await fetch(`/db/${db}/${table}/meta?format=json`);
const json = await r.text();
if (json) {
const obj = JSON.parse(json);
if (!store.columns[db])
Vue.set(store.columns, db, {});
Vue.set(store.columns[db], table, obj);
}
})
}
export async function sharpData(db:string,table:string,args?:any) {
let url = `/db/${db}/${table}?format=json`;
if (args) {
url = appendQueryString(url, args);
}
return await (await fetch(url)).json()
}
Vue.filter('upper', function (value:string) {
return value?.toUpperCase();
});
Vue.filter('json', function (value:any) {
return value && JSON.stringify(value);
});
(async () => { await loadSettings(); })();
(async () => {
for (let db in store.tables) {
try {
let r = await fetch(`/db/${db}/totals?format=json`);
let json = await r.text();
if (json) {
let kvps = JSON.parse(json);
let columnTotals:any = {};
kvps.forEach((x:any) => {
columnTotals[x.key] = x.value;
})
Vue.set(store.totals, db, columnTotals);
}
} catch (e) {
log(`Can't retrieve totals for '${db}':`, e);
}
}
})();
(async () => {
try {
store.desktop = await desktopInfo();
log('In Desktop app:', store.desktop);
} catch (e) {
log(`Not in Desktop app:`, e);
}
})();