xdriver 2.0.1 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/com.js CHANGED
@@ -17,13 +17,6 @@ export function _copy(src, target) {
17
17
  }
18
18
  return target;
19
19
  }
20
- var LogLevel;
21
- (function (LogLevel) {
22
- LogLevel[LogLevel["debug"] = 0] = "debug";
23
- LogLevel[LogLevel["warn"] = 1] = "warn";
24
- LogLevel[LogLevel["info"] = 2] = "info";
25
- LogLevel[LogLevel["error"] = 3] = "error";
26
- })(LogLevel || (LogLevel = {}));
27
20
  export class Logger {
28
21
  constructor(catalog) {
29
22
  this.catalog = catalog;
@@ -40,19 +33,19 @@ export class Logger {
40
33
  return `[${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}.${date.getMilliseconds()}]`;
41
34
  }
42
35
  debug(msg, ...args) {
43
- this.print(console.debug, `%c${this.getFormatDate()} [DEBUG] <${this.catalog}> ${msg}`, ...args, "color: gray;");
36
+ this.print(console.debug, `%c${this.getFormatDate()} [DEBUG] <${this.catalog}> ${msg}`, "color: gray;", ...args);
44
37
  }
45
38
  warn(msg, ...args) {
46
- this.print(console.warn, `%c${this.getFormatDate()} [WARN] <${this.catalog}> ${msg}`, ...args, "color: #FFCC00;");
39
+ this.print(console.warn, `%c${this.getFormatDate()} [WARN] <${this.catalog}> ${msg}`, "color: #FFCC00;", ...args);
47
40
  }
48
41
  info(msg, ...args) {
49
42
  this.print(console.info, `${this.getFormatDate()} [INFO] <${this.catalog}> ${msg}`, ...args);
50
43
  }
51
44
  error(msg, ...args) {
52
- this.print(console.error, `%c${this.getFormatDate()} [ERROR] <${this.catalog}> ${msg}`, ...args, "color: #EF4444;");
45
+ this.print(console.error, `%c${this.getFormatDate()} [ERROR] <${this.catalog}> ${msg}`, "color: #EF4444;", ...args);
53
46
  }
54
47
  success(msg, ...args) {
55
- this.print(console.log, `%c${this.getFormatDate()} [SUCCESS] <${this.catalog}> ${msg}`, ...args, "color: #10B981;");
48
+ this.print(console.log, `%c${this.getFormatDate()} [SUCCESS] <${this.catalog}> ${msg}`, "color: #10B981;", ...args);
56
49
  }
57
50
  static getLogger(catalog = 'default') {
58
51
  return new Logger(catalog);
@@ -0,0 +1,37 @@
1
+ import { IndexdbStatus } from "./const";
2
+ import Table, { ITable, TableMeta } from "./table";
3
+ interface EventMap {
4
+ process: (this: Connection, status: IndexdbStatus) => void;
5
+ success: (this: Connection, connect: IDBDatabase) => void;
6
+ blocked: (this: Connection, event: IDBVersionChangeEvent) => void;
7
+ change: (connect: IDBDatabase, event: IDBVersionChangeEvent) => void;
8
+ error: (evt: Event) => void;
9
+ close: () => void;
10
+ }
11
+ type EventKey = keyof EventMap;
12
+ export default class Connection {
13
+ name: string;
14
+ version: number;
15
+ idbDatabase?: IDBDatabase;
16
+ readonly tableMap: Map<string, Table>;
17
+ private eventMap;
18
+ constructor(database?: string, version?: number);
19
+ on<T extends EventKey>(event: T, handle: EventMap[T]): this;
20
+ get connected(): boolean;
21
+ connect(name?: string, version?: number, upgrade?: (idbDatabase: IDBDatabase, event: IDBVersionChangeEvent) => any): Promise<any>;
22
+ drop(): Promise<Event>;
23
+ close(): void;
24
+ createTable(tableName: string, meta?: Omit<TableMeta, 'name'> & {
25
+ overwrite?: boolean;
26
+ }, idbDatabase?: IDBDatabase): Promise<Table>;
27
+ createTables(tables: Array<string | (TableMeta & {
28
+ overwrite?: boolean;
29
+ })>, meta: (Omit<ITable, "name"> & {
30
+ overwrite?: boolean;
31
+ }) | undefined, idbDatabase: IDBDatabase): Promise<Table[]>;
32
+ dropTable(tableName: string): boolean;
33
+ table(tableName: string): Table;
34
+ exists(table: string): boolean;
35
+ getTables(): Table[];
36
+ }
37
+ export {};
@@ -0,0 +1,190 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { IndexdbStatus, innerDB } from "./const";
11
+ import Table from "./table";
12
+ import { Logger } from './com';
13
+ const logger = Logger.getLogger('Database');
14
+ export default class Connection {
15
+ constructor(database = 'default', version = 1) {
16
+ this.eventMap = {};
17
+ this.name = database;
18
+ this.version = version;
19
+ this.tableMap = new Map();
20
+ }
21
+ on(event, handle) {
22
+ this.eventMap[event] = handle;
23
+ return this;
24
+ }
25
+ get connected() {
26
+ return this.idbDatabase != void 0;
27
+ }
28
+ connect(name, version, upgrade) {
29
+ return __awaiter(this, void 0, void 0, function* () {
30
+ var _a;
31
+ if ((!name || version == void 0) && this.connected) {
32
+ return Promise.resolve(this);
33
+ }
34
+ this.name = name || this.name;
35
+ this.version = version || this.version;
36
+ logger.debug(`Connect to database ${this.name} ${this.version}`);
37
+ const request = innerDB.open(this.name, version);
38
+ (_a = this.eventMap.process) === null || _a === void 0 ? void 0 : _a.call(this, IndexdbStatus.CONNECT_ING);
39
+ request.onblocked = (evt) => {
40
+ var _a, _b;
41
+ logger.warn(`onblocked change from ${evt.oldVersion} to ${evt.newVersion}`, evt);
42
+ (_a = this.eventMap.process) === null || _a === void 0 ? void 0 : _a.call(this, IndexdbStatus.CONNECT_CLOSE);
43
+ (_b = this.eventMap.blocked) === null || _b === void 0 ? void 0 : _b.call(this, evt);
44
+ };
45
+ let returnVal = void 0;
46
+ request.onupgradeneeded = (event) => {
47
+ var _a, _b;
48
+ logger.info(`Version change from <${event.oldVersion}> to <${event.newVersion}>`, event);
49
+ (_a = this.eventMap.process) === null || _a === void 0 ? void 0 : _a.call(this, IndexdbStatus.VERSION_CHANGE);
50
+ const target = event.target;
51
+ this.idbDatabase = target.result;
52
+ (_b = this.eventMap.change) === null || _b === void 0 ? void 0 : _b.call(this, this.idbDatabase, event);
53
+ returnVal = upgrade === null || upgrade === void 0 ? void 0 : upgrade(this.idbDatabase, event);
54
+ };
55
+ return new Promise((resolve, reject) => {
56
+ request.onerror = (e) => {
57
+ var _a, _b;
58
+ logger.error('onerror', e);
59
+ (_a = this.eventMap.process) === null || _a === void 0 ? void 0 : _a.call(this, IndexdbStatus.CONNECT_ERROR);
60
+ (_b = this.eventMap.error) === null || _b === void 0 ? void 0 : _b.call(this, e);
61
+ reject(e);
62
+ };
63
+ request.onsuccess = (e) => {
64
+ var _a, _b;
65
+ logger.debug(`Connect Success`, e);
66
+ const target = e.target;
67
+ let connect = target.result;
68
+ this.idbDatabase = connect;
69
+ let objectStoreNames = connect.objectStoreNames;
70
+ if (objectStoreNames.length) {
71
+ let transaction = connect.transaction(objectStoreNames);
72
+ for (let i = 0; i < objectStoreNames.length; i++) {
73
+ let table = objectStoreNames.item(i);
74
+ if (!table)
75
+ continue;
76
+ let objectStore = transaction.objectStore(table);
77
+ let { indexNames, keyPath: primaryKey, name, autoIncrement = true } = objectStore;
78
+ let indexes = [];
79
+ for (let j = 0; indexNames && j < indexNames.length; j++) {
80
+ let indexName = indexNames.item(j);
81
+ if (!indexName)
82
+ continue;
83
+ let { keyPath, name, multiEntry, unique } = objectStore.index(indexName);
84
+ indexes.push({ name, column: keyPath, unique, multiEntry });
85
+ }
86
+ this.tableMap.set(name, new Table({
87
+ name,
88
+ primaryKey: primaryKey == null ? void 0 : primaryKey,
89
+ autoIncrement,
90
+ indexes
91
+ }, this.idbDatabase));
92
+ }
93
+ transaction.commit();
94
+ }
95
+ (_a = this.eventMap.process) === null || _a === void 0 ? void 0 : _a.call(this, IndexdbStatus.CONNECT_SUCCESS);
96
+ (_b = this.eventMap.success) === null || _b === void 0 ? void 0 : _b.call(this, this.idbDatabase);
97
+ resolve(returnVal || this);
98
+ };
99
+ });
100
+ });
101
+ }
102
+ drop() {
103
+ return new Promise((resolve, reject) => {
104
+ let request = innerDB.deleteDatabase(this.name);
105
+ request.onerror = function (event) {
106
+ reject(event);
107
+ };
108
+ request.onsuccess = function (event) {
109
+ resolve(event);
110
+ };
111
+ this.close();
112
+ });
113
+ }
114
+ close() {
115
+ var _a, _b, _c;
116
+ if (this.connected) {
117
+ (_a = this.eventMap.process) === null || _a === void 0 ? void 0 : _a.call(this, IndexdbStatus.CONNECT_CLOSE);
118
+ (_b = this.idbDatabase) === null || _b === void 0 ? void 0 : _b.close();
119
+ (_c = this.eventMap.close) === null || _c === void 0 ? void 0 : _c.call(this);
120
+ this.idbDatabase = void 0;
121
+ }
122
+ }
123
+ createTable(tableName_1) {
124
+ return __awaiter(this, arguments, void 0, function* (tableName, meta = {}, idbDatabase) {
125
+ var _a, _b;
126
+ const { overwrite = false } = meta;
127
+ if (!overwrite && this.exists(tableName)) {
128
+ throw new Error(`Table ${tableName} is exists`);
129
+ }
130
+ const metadata = Object.assign(Object.assign({}, meta), { name: tableName });
131
+ let { name = '', primaryKey = 'id', autoIncrement = true, indexes = [], rows = [] } = metadata;
132
+ const store = (_a = (idbDatabase || this.idbDatabase)) === null || _a === void 0 ? void 0 : _a.createObjectStore(name, { keyPath: primaryKey, autoIncrement });
133
+ let idxes = indexes.map(({ name, column, unique, multiEntry }) => {
134
+ store === null || store === void 0 ? void 0 : store.createIndex(name, column, { unique, multiEntry });
135
+ return { name, column, unique, multiEntry };
136
+ });
137
+ (_b = metadata.rows) === null || _b === void 0 ? void 0 : _b.forEach(row => store === null || store === void 0 ? void 0 : store.add(row));
138
+ let table = new Table({ name, primaryKey, autoIncrement, indexes: idxes }, idbDatabase || this.idbDatabase);
139
+ this.tableMap.set(name, table);
140
+ return table;
141
+ });
142
+ }
143
+ createTables(tables_1) {
144
+ return __awaiter(this, arguments, void 0, function* (tables, meta = {}, idbDatabase) {
145
+ return new Promise((resolve) => {
146
+ const createTables = (idbDatabase) => __awaiter(this, void 0, void 0, function* () {
147
+ let list = yield Promise.all(tables.map(table => {
148
+ if (typeof table === 'string') {
149
+ return this.createTable(table, meta, idbDatabase);
150
+ }
151
+ else {
152
+ return this.createTable(table.name, Object.assign(Object.assign({}, meta), table), idbDatabase);
153
+ }
154
+ }));
155
+ resolve(list);
156
+ });
157
+ if (idbDatabase) {
158
+ createTables(idbDatabase);
159
+ }
160
+ else {
161
+ this.connect(this.name, ++this.version, createTables);
162
+ }
163
+ });
164
+ });
165
+ }
166
+ dropTable(tableName) {
167
+ var _a;
168
+ if (this.exists(tableName)) {
169
+ (_a = this.idbDatabase) === null || _a === void 0 ? void 0 : _a.deleteObjectStore(tableName);
170
+ this.tableMap.delete(tableName);
171
+ return true;
172
+ }
173
+ logger.error(`Table ${tableName} is not exists`);
174
+ throw new Error(`Table ${tableName} is not exists`);
175
+ }
176
+ table(tableName) {
177
+ const table = this.tableMap.get(tableName);
178
+ if (!table) {
179
+ logger.error(`Table ${tableName} is not exists`);
180
+ throw new Error(`Table ${tableName} is not exists`);
181
+ }
182
+ return table;
183
+ }
184
+ exists(table) {
185
+ return this.tableMap.has(table);
186
+ }
187
+ getTables() {
188
+ return [...this.tableMap.values()];
189
+ }
190
+ }
package/lib/const.d.ts CHANGED
@@ -9,13 +9,13 @@ export declare enum IndexdbStatus {
9
9
  VERSION_CHANGE = 99
10
10
  }
11
11
  export declare class KeyRange {
12
- static leq(x: any): IDBKeyRange;
13
- static lt(x: any): IDBKeyRange;
14
- static geq(x: any): IDBKeyRange;
15
- static gt(x: any): IDBKeyRange;
16
- static between(x: any, y: any): IDBKeyRange;
17
- static gt_lt(x: any, y: any): IDBKeyRange;
18
- static gt_leq(x: any, y: any): IDBKeyRange;
19
- static geq_lt(x: any, y: any): IDBKeyRange;
20
- static eq(x: any, y: any): IDBKeyRange;
12
+ static leq(val: any): IDBKeyRange;
13
+ static lt(val: any): IDBKeyRange;
14
+ static geq(val: any): IDBKeyRange;
15
+ static gt(val: any): IDBKeyRange;
16
+ static between(low: any, upper: any): IDBKeyRange;
17
+ static gt_lt(low: any, upper: any): IDBKeyRange;
18
+ static gt_leq(low: any, upper: any): IDBKeyRange;
19
+ static geq_lt(low: any, upper: any): IDBKeyRange;
20
+ static eq(val: any): IDBKeyRange;
21
21
  }
package/lib/const.js CHANGED
@@ -11,31 +11,31 @@ export var IndexdbStatus;
11
11
  IndexdbStatus[IndexdbStatus["VERSION_CHANGE"] = 99] = "VERSION_CHANGE";
12
12
  })(IndexdbStatus || (IndexdbStatus = {}));
13
13
  export class KeyRange {
14
- static leq(x) {
15
- return IDBKeyRange.upperBound(x);
14
+ static leq(val) {
15
+ return IDBKeyRange.upperBound(val);
16
16
  }
17
- static lt(x) {
18
- return IDBKeyRange.upperBound(x, true);
17
+ static lt(val) {
18
+ return IDBKeyRange.upperBound(val, true);
19
19
  }
20
- static geq(x) {
21
- return IDBKeyRange.lowerBound(x);
20
+ static geq(val) {
21
+ return IDBKeyRange.lowerBound(val);
22
22
  }
23
- static gt(x) {
24
- return IDBKeyRange.lowerBound(x, true);
23
+ static gt(val) {
24
+ return IDBKeyRange.lowerBound(val, true);
25
25
  }
26
- static between(x, y) {
27
- return IDBKeyRange.bound(x, y);
26
+ static between(low, upper) {
27
+ return IDBKeyRange.bound(low, upper);
28
28
  }
29
- static gt_lt(x, y) {
30
- return IDBKeyRange.bound(x, y, true, true);
29
+ static gt_lt(low, upper) {
30
+ return IDBKeyRange.bound(low, upper, true, true);
31
31
  }
32
- static gt_leq(x, y) {
33
- return IDBKeyRange.bound(x, y, true, false);
32
+ static gt_leq(low, upper) {
33
+ return IDBKeyRange.bound(low, upper, true, false);
34
34
  }
35
- static geq_lt(x, y) {
36
- return IDBKeyRange.bound(x, y, false, true);
35
+ static geq_lt(low, upper) {
36
+ return IDBKeyRange.bound(low, upper, false, true);
37
37
  }
38
- static eq(x, y) {
39
- return IDBKeyRange.only(x);
38
+ static eq(val) {
39
+ return IDBKeyRange.only(val);
40
40
  }
41
41
  }
package/lib/database.d.ts CHANGED
@@ -1,31 +1,18 @@
1
- import { IndexdbStatus } from "./const";
2
- import Table, { Metadata } from "./table";
3
- interface EventMap {
4
- process: (this: Database, status: IndexdbStatus) => void;
5
- success: (this: Database, connect: IDBDatabase) => void;
6
- blocked: (this: Database, event: IDBVersionChangeEvent) => void;
7
- change: (connect: any) => void;
8
- error: (evt: Event) => void;
9
- close: () => void;
1
+ import Connection from "./connection";
2
+ import { Row, Pagination, RowPacket } from "./table";
3
+ export default class Database extends Connection {
4
+ query<R extends Row>(table: string, query?: IDBValidKey | IDBKeyRange, count?: number): Promise<RowPacket<R>>;
5
+ select<R extends Row>(table: string, key?: IDBValidKey | IDBKeyRange, index?: string, count?: number): Promise<RowPacket<R>>;
6
+ queryByKey<R extends Row>(table: string, key: IDBValidKey | IDBKeyRange): Promise<RowPacket<R>>;
7
+ queryByIndex<R extends Row>(table: string, indexName: string, key?: IDBValidKey | IDBKeyRange, count?: number): Promise<RowPacket<R>>;
8
+ queryById<R extends Row>(table: string, id: any | Array<any>, indexName?: string): Promise<R>;
9
+ count(table: string, key: IDBValidKey | IDBKeyRange): Promise<number>;
10
+ insert(table: string, data: Array<Record<string, any>>): Promise<IDBValidKey[]>;
11
+ update(table: string, modify: Row, key?: IDBValidKey | IDBKeyRange | null): Promise<IDBValidKey>;
12
+ delete(table: string, key: IDBValidKey | IDBKeyRange): Promise<any[]>;
13
+ truncate(table: string): Promise<void>;
14
+ getPagination<R extends Row>(table: string, pageSize?: number): Promise<Pagination<R>>;
15
+ scan<R extends Row>(table: string, key?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection, indexName?: string): Promise<RowPacket<R>>;
16
+ getAllData<R extends Row>(table: string): Promise<Array<R>>;
17
+ paginate<R extends Row>(table: string, pageNo?: number, pageSize?: number, key?: IDBValidKey | IDBKeyRange, indexName?: string): Promise<RowPacket<R>>;
10
18
  }
11
- type EventKey = keyof EventMap;
12
- export default class Database {
13
- private name;
14
- private version;
15
- database?: IDBDatabase;
16
- readonly tableMap: Map<string, Table>;
17
- private eventMap;
18
- constructor(database: string, version?: number);
19
- on<T extends EventKey>(event: T, handle: EventMap[T]): this;
20
- get connected(): boolean;
21
- connect(name?: string, version?: number): Promise<Database>;
22
- drop(): Promise<unknown>;
23
- close(): void;
24
- createTable(tableName: string, meta?: Omit<Metadata, 'name'>): Table;
25
- createTables(tables: Array<string>, meta?: Omit<Metadata, 'name' | 'rows'>): Table[];
26
- dropTable(tableName: string): boolean;
27
- table(tableName: string): Table | undefined;
28
- exists(table: string): boolean;
29
- getTables(): MapIterator<Table>;
30
- }
31
- export {};
package/lib/database.js CHANGED
@@ -1,146 +1,62 @@
1
- import { IndexdbStatus, innerDB } from "./const";
2
- import Table from "./table";
3
- import { Logger } from './com';
4
- const logger = Logger.getLogger('Database');
5
- export default class Database {
6
- constructor(database, version = 1) {
7
- this.eventMap = {};
8
- this.name = database;
9
- this.version = version;
10
- this.tableMap = new Map();
11
- }
12
- on(event, handle) {
13
- this.eventMap[event] = handle;
14
- return this;
15
- }
16
- get connected() {
17
- return this.database != void 0;
18
- }
19
- connect(name, version) {
20
- var _a;
21
- if (!name && version == void 0 && this.connected) {
22
- return Promise.resolve(this);
23
- }
24
- this.name = name || this.name;
25
- this.version = version || this.version;
26
- const request = innerDB.open(this.name, version);
27
- (_a = this.eventMap.process) === null || _a === void 0 ? void 0 : _a.call(this, IndexdbStatus.CONNECT_ING);
28
- request.onerror = (e) => {
29
- var _a, _b;
30
- logger.error('onerror', e);
31
- (_a = this.eventMap.process) === null || _a === void 0 ? void 0 : _a.call(this, IndexdbStatus.CONNECT_ERROR);
32
- (_b = this.eventMap.error) === null || _b === void 0 ? void 0 : _b.call(this, e);
33
- };
34
- request.onblocked = (evt) => {
35
- var _a, _b;
36
- logger.warn(`onblocked change from ${evt.oldVersion} to ${evt.newVersion}`, evt);
37
- (_a = this.eventMap.process) === null || _a === void 0 ? void 0 : _a.call(this, IndexdbStatus.CONNECT_CLOSE);
38
- (_b = this.eventMap.blocked) === null || _b === void 0 ? void 0 : _b.call(this, evt);
39
- };
40
- return new Promise((resolve, reject) => {
41
- request.onupgradeneeded = (event) => {
42
- var _a, _b;
43
- logger.info(`Version change from <${event.oldVersion}> to <${event.newVersion}>`, event);
44
- (_a = this.eventMap.process) === null || _a === void 0 ? void 0 : _a.call(this, IndexdbStatus.VERSION_CHANGE);
45
- const target = event.target;
46
- this.database = target.result;
47
- (_b = this.eventMap.change) === null || _b === void 0 ? void 0 : _b.call(this, this.database);
48
- };
49
- request.onsuccess = (e) => {
50
- var _a, _b;
51
- logger.info(`Connect Success`, e);
52
- const target = e.target;
53
- let connect = target.result;
54
- this.database = connect;
55
- let objectStoreNames = connect.objectStoreNames;
56
- if (objectStoreNames.length) {
57
- let transaction = connect.transaction(objectStoreNames);
58
- for (let i = 0; i < objectStoreNames.length; i++) {
59
- let table = objectStoreNames.item(i);
60
- if (!table)
61
- continue;
62
- let objectStore = transaction.objectStore(table);
63
- let { indexNames, keyPath: primaryKey, name, autoIncrement = true } = objectStore;
64
- let indexes = [];
65
- for (let j = 0; indexNames && j < indexNames.length; j++) {
66
- let indexName = indexNames.item(j);
67
- if (!indexName)
68
- continue;
69
- let { keyPath, name, multiEntry, unique } = objectStore.index(indexName);
70
- indexes.push({ name, column: keyPath, unique, multiEntry });
71
- }
72
- this.tableMap.set(name, new Table({ name, primaryKey: primaryKey == null ? void 0 : primaryKey, autoIncrement, indexes }, this.database));
73
- }
74
- }
75
- (_a = this.eventMap.process) === null || _a === void 0 ? void 0 : _a.call(this, IndexdbStatus.CONNECT_SUCCESS);
76
- (_b = this.eventMap.success) === null || _b === void 0 ? void 0 : _b.call(this, this.database);
77
- resolve(this);
78
- };
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import Connection from "./connection";
11
+ export default class Database extends Connection {
12
+ query(table, query, count = 1000) {
13
+ return this.table(table).query(query, count);
14
+ }
15
+ select(table, key, index, count = 1000) {
16
+ return this.table(table).select(key, count, index);
17
+ }
18
+ queryByKey(table, key) {
19
+ return this.table(table).queryByKey(key);
20
+ }
21
+ queryByIndex(table, indexName, key, count) {
22
+ return __awaiter(this, void 0, void 0, function* () {
23
+ return this.table(table).queryByIndex(indexName, key, count);
79
24
  });
80
25
  }
81
- drop() {
82
- return new Promise((resolve, reject) => {
83
- let request = innerDB.deleteDatabase(this.name);
84
- request.onerror = function (event) {
85
- reject(event);
86
- };
87
- request.onsuccess = function (event) {
88
- resolve(event);
89
- };
90
- this.close();
26
+ queryById(table, id, indexName) {
27
+ return __awaiter(this, void 0, void 0, function* () {
28
+ return this.table(table).queryById(id, indexName);
91
29
  });
92
30
  }
93
- close() {
94
- var _a, _b, _c;
95
- if (this.connected) {
96
- (_a = this.eventMap.process) === null || _a === void 0 ? void 0 : _a.call(this, IndexdbStatus.CONNECT_CLOSE);
97
- (_b = this.database) === null || _b === void 0 ? void 0 : _b.close();
98
- (_c = this.eventMap.close) === null || _c === void 0 ? void 0 : _c.call(this);
99
- this.database = void 0;
100
- }
31
+ count(table, key) {
32
+ return this.table(table).count(key);
101
33
  }
102
- createTable(tableName, meta = {}) {
103
- var _a, _b;
104
- if (this.exists(tableName)) {
105
- throw new Error(`Table ${tableName} is exists`);
106
- }
107
- const metadata = Object.assign(Object.assign({}, meta), { name: tableName });
108
- let { name = '', primaryKey = 'id', autoIncrement = true, indexes = [], rows = [] } = metadata;
109
- const store = (_a = this.database) === null || _a === void 0 ? void 0 : _a.createObjectStore(name, { keyPath: primaryKey, autoIncrement });
110
- let idxes = indexes.map(({ name, column, unique, multiEntry }) => {
111
- store === null || store === void 0 ? void 0 : store.createIndex(name, column, { unique, multiEntry });
112
- return { name, column, unique, multiEntry };
113
- });
114
- (_b = metadata.rows) === null || _b === void 0 ? void 0 : _b.forEach(row => store === null || store === void 0 ? void 0 : store.add(row));
115
- let tab = new Table({ name, primaryKey, autoIncrement, indexes: idxes }, this.database);
116
- this.tableMap.set(name, tab);
117
- return tab;
34
+ insert(table, data) {
35
+ return this.table(table).insert(data);
118
36
  }
119
- createTables(tables, meta = {}) {
120
- return tables.map(table => {
121
- return this.createTable(table, meta);
122
- });
37
+ update(table, modify, key) {
38
+ return this.table(table).update(modify, key);
123
39
  }
124
- dropTable(tableName) {
125
- var _a;
126
- if (this.exists(tableName)) {
127
- (_a = this.database) === null || _a === void 0 ? void 0 : _a.deleteObjectStore(tableName);
128
- this.tableMap.delete(tableName);
129
- return true;
130
- }
131
- return false;
40
+ delete(table, key) {
41
+ return this.table(table).delete(key);
132
42
  }
133
- table(tableName) {
134
- const table = this.tableMap.get(tableName);
135
- if (!table) {
136
- logger.error(`Table ${tableName} is not exists`);
137
- }
138
- return table;
43
+ truncate(table) {
44
+ return this.table(table).truncate();
139
45
  }
140
- exists(table) {
141
- return this.tableMap.has(table);
46
+ getPagination(table, pageSize = 10) {
47
+ return this.table(table).getPagination(pageSize, 1);
142
48
  }
143
- getTables() {
144
- return this.tableMap.values();
49
+ scan(table_1, key_1) {
50
+ return __awaiter(this, arguments, void 0, function* (table, key, direction = 'next', indexName) {
51
+ return this.table(table).scan(key, direction, indexName);
52
+ });
53
+ }
54
+ getAllData(table) {
55
+ return this.table(table).getAllData();
56
+ }
57
+ paginate(table_1) {
58
+ return __awaiter(this, arguments, void 0, function* (table, pageNo = 1, pageSize = 10, key, indexName) {
59
+ return this.table(table).paginate(pageNo, pageSize, key, indexName);
60
+ });
145
61
  }
146
62
  }
package/lib/index.d.ts CHANGED
@@ -1,6 +1,15 @@
1
1
  import { IndexdbStatus, KeyRange } from "./const";
2
- import Driver from "./driver";
3
2
  import Database from "./database";
4
- import Table from "./table";
5
- export { IndexdbStatus, KeyRange, Database, Table, Driver };
3
+ import Connection from "./connection";
4
+ import Table, { TableMeta } from "./table";
5
+ export { IndexdbStatus, KeyRange, Connection, Table };
6
+ declare class Driver {
7
+ private readonly name;
8
+ private version;
9
+ private readonly tables;
10
+ constructor(name: string, version?: number);
11
+ defineTables(...tables: Array<TableMeta>): this;
12
+ private hasChange;
13
+ connect(version?: number): Promise<Database>;
14
+ }
6
15
  export default Driver;
package/lib/index.js CHANGED
@@ -1,6 +1,140 @@
1
- import { IndexdbStatus, KeyRange } from "./const";
2
- import Driver from "./driver";
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { IndexdbStatus, innerDB, KeyRange } from "./const";
3
11
  import Database from "./database";
12
+ import Connection from "./connection";
4
13
  import Table from "./table";
5
- export { IndexdbStatus, KeyRange, Database, Table, Driver };
14
+ import { Logger } from "./com";
15
+ export { IndexdbStatus, KeyRange, Connection, Table };
16
+ const logger = Logger.getLogger("Driver");
17
+ class Driver {
18
+ constructor(name, version = 0) {
19
+ this.tables = [];
20
+ this.name = name;
21
+ this.version = version;
22
+ }
23
+ defineTables(...tables) {
24
+ this.tables.push(...tables);
25
+ logger.debug(`Define tables: ${tables.map(t => t.name).join(', ')}`);
26
+ return this;
27
+ }
28
+ hasChange(database) {
29
+ return __awaiter(this, void 0, void 0, function* () {
30
+ var _a;
31
+ const existTables = database.getTables();
32
+ const defineTables = this.tables;
33
+ if (existTables.length !== defineTables.length) {
34
+ logger.warn(`Table count is changed.`);
35
+ return true;
36
+ }
37
+ let change = false;
38
+ for (let table of defineTables) {
39
+ if (!existTables.some(t => t.name === table.name)) {
40
+ logger.warn(`Table ${table.name} is added, create it.`);
41
+ change = true;
42
+ break;
43
+ }
44
+ }
45
+ if (change) {
46
+ return change;
47
+ }
48
+ for (let existTable of existTables) {
49
+ const tableMeta = defineTables.find(t => t.name === existTable.name);
50
+ if (!tableMeta) {
51
+ logger.warn(`Table ${existTable.name} is removed, drop it.`);
52
+ change = true;
53
+ break;
54
+ }
55
+ let existIndexes = existTable.indexes || [];
56
+ for (let existIndex of existIndexes) {
57
+ const metaIndex = (_a = tableMeta.indexes) === null || _a === void 0 ? void 0 : _a.find(i => i.name === existIndex.name);
58
+ if (!metaIndex) {
59
+ logger.warn(`Table ${existTable.name} index ${existIndex.name} is removed, drop it.`);
60
+ change = true;
61
+ break;
62
+ }
63
+ }
64
+ if (change) {
65
+ break;
66
+ }
67
+ for (let metaIndex of tableMeta.indexes || []) {
68
+ const index = existIndexes.find(i => i.name === metaIndex.name);
69
+ if (!index) {
70
+ logger.warn(`Table ${existTable.name} index ${metaIndex.name} is added, create it.`);
71
+ change = true;
72
+ break;
73
+ }
74
+ }
75
+ if (change) {
76
+ break;
77
+ }
78
+ }
79
+ return change;
80
+ });
81
+ }
82
+ connect(version) {
83
+ return __awaiter(this, void 0, void 0, function* () {
84
+ const databases = yield innerDB.databases();
85
+ const existsDB = databases.find(db => db.name === this.name);
86
+ if (existsDB) {
87
+ logger.info(`Database ${this.name} exists`);
88
+ this.version = existsDB.version || this.version;
89
+ }
90
+ if (version) {
91
+ this.version = Math.max(this.version, version);
92
+ }
93
+ logger.debug(`Connect to database ${this.name} ${this.version}`);
94
+ const database = new Database(this.name, this.version);
95
+ database.on('change', (idbDatabase, event) => {
96
+ const existTables = [...idbDatabase.objectStoreNames];
97
+ if (existTables.length) {
98
+ for (let tableName of existTables) {
99
+ let existTable = this.tables.find(t => t.name === tableName);
100
+ if (!existTable) {
101
+ logger.warn(`Table ${tableName} is removed, drop it.`);
102
+ database.dropTable(tableName);
103
+ continue;
104
+ }
105
+ const transaction = event.target.transaction;
106
+ if (!transaction) {
107
+ logger.warn(`Transaction not support`);
108
+ continue;
109
+ }
110
+ let objectStore = transaction.objectStore(tableName);
111
+ if (!objectStore) {
112
+ logger.warn(`Table ${tableName} not exists`);
113
+ continue;
114
+ }
115
+ let { indexNames } = objectStore;
116
+ for (let indexName of indexNames) {
117
+ objectStore.deleteIndex(indexName);
118
+ }
119
+ for (let index of existTable.indexes || []) {
120
+ objectStore.createIndex(index.name, index.column, Object.assign({}, index));
121
+ }
122
+ }
123
+ }
124
+ for (let table of this.tables) {
125
+ if (existTables.indexOf(table.name) < 0) {
126
+ logger.info(`Table ${table.name} is not exist, create it.`);
127
+ database.createTable(table.name, table);
128
+ }
129
+ }
130
+ });
131
+ yield database.connect();
132
+ if (yield this.hasChange(database)) {
133
+ database.close();
134
+ yield database.connect(this.name, ++this.version);
135
+ }
136
+ return database;
137
+ });
138
+ }
139
+ }
6
140
  export default Driver;
package/lib/table.d.ts CHANGED
@@ -12,9 +12,43 @@ export type ITable = {
12
12
  };
13
13
  export type Row = Record<string, any>;
14
14
  export type Rows = Array<Row>;
15
- export type Metadata = ITable & {
15
+ export type TableMeta = ITable & {
16
16
  rows?: Rows;
17
17
  };
18
+ export declare class RowPacket<T extends Row> extends Array<T> {
19
+ constructor(rows?: Array<T>);
20
+ distinct(column?: string | ((row: T) => any)): Array<T>;
21
+ mapping<K, T>(keyFn: (row: T, index: number, array: Array<T>) => K): Map<K, T>;
22
+ mapping<K, V>(keyFn: (row: T, index: number, array: Array<T>) => K, valFn: (row: T, index: number, array: Array<T>) => V): Map<K, V>;
23
+ group<K, V>(key: keyof T | ((row: T, index: number, array: Array<T>) => K)): Map<K, Array<T>>;
24
+ group<K, V>(key: keyof T | ((row: T, index: number, array: Array<T>) => K), valFn: (row: T, index: number, array: Array<T>) => V): Map<K, Array<V>>;
25
+ max(keyFn: keyof T | ((row: T, index: number, array: Array<T>) => number)): {
26
+ value: number;
27
+ rows: Array<T>;
28
+ };
29
+ min(keyFn: keyof T | ((row: T, index: number, array: Array<T>) => number)): {
30
+ value: number;
31
+ rows: Array<T>;
32
+ };
33
+ sum(keyFn: keyof T | ((row: T, index: number, array: Array<T>) => number)): number;
34
+ average(keyFn: keyof T | ((row: T, index: number, array: Array<T>) => number)): number;
35
+ }
36
+ export declare class Pagination<T extends Row> {
37
+ private readonly _data;
38
+ private readonly _pageSize;
39
+ private _pageIndex;
40
+ private readonly _total;
41
+ constructor(data: Array<T>, pageSize?: number, pageIndex?: number);
42
+ get totalPage(): number;
43
+ get total(): number;
44
+ get pageIndex(): number;
45
+ get pageSize(): number;
46
+ get hasNext(): boolean;
47
+ get hasPrev(): boolean;
48
+ get data(): Array<any>;
49
+ prev(): boolean;
50
+ next(): boolean;
51
+ }
18
52
  export default class Table implements ITable {
19
53
  readonly name: string;
20
54
  readonly primaryKey: string | string[];
@@ -22,19 +56,21 @@ export default class Table implements ITable {
22
56
  readonly indexes: Array<Index>;
23
57
  readonly database?: IDBDatabase;
24
58
  constructor(table: ITable | string, database?: IDBDatabase);
25
- insert(data: Row | Rows): Promise<any[]>;
26
- update(modify: Row, key?: IDBValidKey | IDBKeyRange | null, count?: number): Promise<IDBValidKey>;
27
- merge(row: Row): Promise<IDBValidKey> | Promise<any[]>;
59
+ get meta(): TableMeta;
60
+ insert(data: Row | Rows): Promise<Array<IDBValidKey>>;
61
+ update(modify: Row, key?: IDBValidKey | IDBKeyRange | null): Promise<IDBValidKey>;
28
62
  delete(key: IDBValidKey | IDBKeyRange): Promise<any[]>;
29
- clear(): Promise<undefined>;
63
+ truncate(): Promise<void>;
30
64
  dropIndex(name: string): void;
31
65
  keys(key?: IDBValidKey | IDBKeyRange | null, count?: number): Promise<IDBValidKey[]>;
32
66
  count(key?: IDBValidKey | IDBKeyRange): Promise<number>;
33
- query(key?: IDBValidKey | IDBKeyRange, count?: number): Promise<Rows>;
34
- select(key?: IDBValidKey | IDBKeyRange, count?: number, index?: string): Promise<Rows>;
35
- queryByKey(key: IDBValidKey | IDBKeyRange): Promise<Row>;
36
- fetch(key?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): Promise<Rows>;
37
- queryByIndex(indexName: string, key?: IDBValidKey | IDBKeyRange, count?: number): Promise<Rows>;
38
- deplete(key?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): Promise<Rows>;
39
- multiple(indexName: string, key?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection): Promise<Rows>;
67
+ query<R extends Row>(key?: IDBValidKey | IDBKeyRange, count?: number): Promise<RowPacket<R>>;
68
+ queryByIndex<R extends Row>(indexName: string, key?: IDBValidKey | IDBKeyRange, count?: number): Promise<RowPacket<R>>;
69
+ select<R extends Row>(key?: IDBValidKey | IDBKeyRange, count?: number, indexName?: string): Promise<RowPacket<R>>;
70
+ queryByKey<R extends Row>(key: IDBValidKey | IDBKeyRange): Promise<RowPacket<R>>;
71
+ paginate<R extends Row>(pageNo?: number, pageSize?: number, key?: IDBValidKey | IDBKeyRange, indexName?: string): Promise<RowPacket<R>>;
72
+ queryById<R extends Row>(id: any | Array<any>, indexName?: string): Promise<R>;
73
+ scan<R extends Row>(key?: IDBValidKey | IDBKeyRange, direction?: IDBCursorDirection, indexName?: string): Promise<RowPacket<R>>;
74
+ getAllData<R extends Row>(): Promise<Array<R>>;
75
+ getPagination<R extends Row>(pageSize?: number, pageIndex?: number): Promise<Pagination<R>>;
40
76
  }
package/lib/table.js CHANGED
@@ -7,7 +7,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- import { _copy, _instance, Logger } from "./com";
10
+ import { Logger } from "./com";
11
11
  const logger = Logger.getLogger('Table');
12
12
  const _getObjectStore = (table, mode = 'readonly') => {
13
13
  var _a;
@@ -33,19 +33,163 @@ const _request = (request) => __awaiter(void 0, void 0, void 0, function* () {
33
33
  };
34
34
  });
35
35
  });
36
+ export class RowPacket extends Array {
37
+ constructor(rows = []) {
38
+ super(...rows);
39
+ }
40
+ distinct(column) {
41
+ if (!column) {
42
+ return this;
43
+ }
44
+ let set = new Set();
45
+ return this.filter(row => {
46
+ let union = null;
47
+ if (column !== void 0) {
48
+ union = typeof column === 'function' ? column(row) : row[column];
49
+ }
50
+ else {
51
+ union = row;
52
+ }
53
+ if (!set.has(union)) {
54
+ set.add(union);
55
+ return true;
56
+ }
57
+ return false;
58
+ });
59
+ }
60
+ mapping(keyFn, valFn) {
61
+ if (!keyFn)
62
+ throw new Error('Undefined group by field');
63
+ let mapping = new Map();
64
+ this.forEach((item, index, array) => {
65
+ let unionKey = keyFn.call(this, item, index, array);
66
+ if (mapping.has(unionKey)) {
67
+ throw new Error(`${unionKey} duplicate error`);
68
+ }
69
+ mapping.set(unionKey, valFn ? valFn(item, index, array) : item);
70
+ });
71
+ return mapping;
72
+ }
73
+ group(key, valFn) {
74
+ if (!key)
75
+ throw new Error('Undefined group by field');
76
+ let group = new Map();
77
+ this.forEach((item, index, array) => {
78
+ var _a;
79
+ let unionKey = typeof key === 'function' ? key.call(this, item, index, array) : item[key];
80
+ let value = valFn ? valFn(item, index, this) : item;
81
+ if (!group.has(unionKey)) {
82
+ group.set(unionKey, [value]);
83
+ }
84
+ else {
85
+ (_a = group.get(unionKey)) === null || _a === void 0 ? void 0 : _a.push(value);
86
+ }
87
+ });
88
+ return group;
89
+ }
90
+ max(keyFn) {
91
+ let max = 0;
92
+ let maxRows = [];
93
+ this.forEach((item, index, array) => {
94
+ let unionKey = typeof keyFn === 'function' ? keyFn.call(this, item, index, array) : item[keyFn];
95
+ if (unionKey > max) {
96
+ max = unionKey;
97
+ maxRows = [item];
98
+ }
99
+ else if (unionKey === max) {
100
+ maxRows.push(item);
101
+ }
102
+ });
103
+ return {
104
+ value: max,
105
+ rows: maxRows
106
+ };
107
+ }
108
+ min(keyFn) {
109
+ let min = 0;
110
+ let minRows = [];
111
+ this.forEach((item, index, array) => {
112
+ let unionKey = typeof keyFn === 'function' ? keyFn.call(this, item, index, array) : item[keyFn];
113
+ if (unionKey < min) {
114
+ min = unionKey;
115
+ minRows = [item];
116
+ }
117
+ else if (unionKey === min) {
118
+ minRows.push(item);
119
+ }
120
+ });
121
+ return {
122
+ value: min,
123
+ rows: minRows
124
+ };
125
+ }
126
+ sum(keyFn) {
127
+ return this.reduce((sum, item, index, array) => {
128
+ return sum + (typeof keyFn === 'function' ? keyFn.call(this, item, index, array) : item[keyFn]);
129
+ }, 0);
130
+ }
131
+ average(keyFn) {
132
+ return this.sum(keyFn) / this.length;
133
+ }
134
+ }
135
+ export class Pagination {
136
+ constructor(data, pageSize = 10, pageIndex = 1) {
137
+ this._data = data;
138
+ this._pageSize = pageSize < 1 ? 10 : pageSize;
139
+ this._pageIndex = pageIndex < 0 ? 1 : pageIndex;
140
+ this._total = data.length;
141
+ }
142
+ get totalPage() {
143
+ return Math.ceil(this._total / this._pageSize);
144
+ }
145
+ get total() {
146
+ return this._total;
147
+ }
148
+ get pageIndex() {
149
+ return this._pageIndex;
150
+ }
151
+ get pageSize() {
152
+ return this._pageSize;
153
+ }
154
+ get hasNext() {
155
+ return this._pageIndex * this._pageSize < this._total;
156
+ }
157
+ get hasPrev() {
158
+ return this._pageIndex > 1;
159
+ }
160
+ get data() {
161
+ let start = (this._pageIndex - 1) * this._pageSize;
162
+ let end = start + this._pageSize;
163
+ return this._data.slice(start, end);
164
+ }
165
+ prev() {
166
+ if (this.hasPrev) {
167
+ this._pageIndex--;
168
+ return true;
169
+ }
170
+ return false;
171
+ }
172
+ next() {
173
+ if (this.hasNext) {
174
+ this._pageIndex++;
175
+ return true;
176
+ }
177
+ return false;
178
+ }
179
+ }
36
180
  export default class Table {
37
181
  constructor(table, database) {
38
182
  this.primaryKey = "id";
39
183
  this.autoIncrement = false;
40
184
  this.indexes = [];
41
- let metadata;
185
+ let tableMeta;
42
186
  if (typeof table === 'string') {
43
- metadata = { name: table };
187
+ tableMeta = { name: table };
44
188
  }
45
189
  else {
46
- metadata = Object.assign({}, table);
190
+ tableMeta = Object.assign({}, table);
47
191
  }
48
- const { name = '', primaryKey = 'id', autoIncrement = true, indexes = [] } = metadata;
192
+ const { name = '', primaryKey = 'id', autoIncrement = true, indexes = [] } = tableMeta;
49
193
  this.name = name;
50
194
  this.primaryKey = primaryKey;
51
195
  this.autoIncrement = autoIncrement;
@@ -54,6 +198,14 @@ export default class Table {
54
198
  return Object.assign({ unique: false, multiEntry: false }, idx);
55
199
  });
56
200
  }
201
+ get meta() {
202
+ return {
203
+ name: this.name,
204
+ primaryKey: this.primaryKey,
205
+ autoIncrement: this.autoIncrement,
206
+ indexes: this.indexes
207
+ };
208
+ }
57
209
  insert(data) {
58
210
  return __awaiter(this, void 0, void 0, function* () {
59
211
  const store = _getObjectStore(this, 'readwrite');
@@ -66,34 +218,12 @@ export default class Table {
66
218
  return results;
67
219
  });
68
220
  }
69
- update(modify, key, count) {
221
+ update(modify, key) {
70
222
  return __awaiter(this, void 0, void 0, function* () {
71
223
  const store = _getObjectStore(this, 'readwrite');
72
- if (!key || !_instance(key, IDBKeyRange)) {
73
- return _request(store.put(modify, key));
74
- }
75
- let rows = yield _request(store.getAll(key, count));
76
- rows = _instance(rows, Array) ? rows : [rows];
77
- let results = [];
78
- for (let row of rows) {
79
- let rs = yield _request(store.put(_copy(modify, row)));
80
- results.push(rs);
81
- }
82
- return results;
224
+ return _request(store.put(modify, key));
83
225
  });
84
226
  }
85
- merge(row) {
86
- let { primaryKey } = this;
87
- let keys = Array.isArray(primaryKey) ? primaryKey : [primaryKey];
88
- let keyArray = [];
89
- for (let key of keys) {
90
- keyArray.push(row[key]);
91
- }
92
- if (keyArray.length) {
93
- return this.update(row, keyArray);
94
- }
95
- return this.insert(row);
96
- }
97
227
  delete(key) {
98
228
  return __awaiter(this, void 0, void 0, function* () {
99
229
  if (!key) {
@@ -105,7 +235,7 @@ export default class Table {
105
235
  return rows;
106
236
  });
107
237
  }
108
- clear() {
238
+ truncate() {
109
239
  return _request(_getObjectStore(this, 'readwrite').clear());
110
240
  }
111
241
  dropIndex(name) {
@@ -118,66 +248,90 @@ export default class Table {
118
248
  return _request(_getObjectStore(this).count(key));
119
249
  }
120
250
  query(key, count) {
121
- return _request(_getObjectStore(this).getAll(key, count));
251
+ return __awaiter(this, void 0, void 0, function* () {
252
+ let rows = yield _request(_getObjectStore(this).getAll(key, count));
253
+ return new RowPacket(rows);
254
+ });
255
+ }
256
+ queryByIndex(indexName, key, count) {
257
+ return __awaiter(this, void 0, void 0, function* () {
258
+ const store = _getObjectStore(this);
259
+ const index = store.index(indexName);
260
+ let rows = yield _request(index.getAll(key || null, count));
261
+ return new RowPacket(rows);
262
+ });
122
263
  }
123
- select(key, count, index) {
124
- if (!index) {
264
+ select(key, count, indexName) {
265
+ if (!indexName) {
125
266
  return this.query(key, count);
126
267
  }
127
- return this.queryByIndex(index, key, count);
268
+ return this.queryByIndex(indexName, key, count);
128
269
  }
129
270
  queryByKey(key) {
130
- return _request(_getObjectStore(this).get(key));
131
- }
132
- fetch(key, direction) {
133
271
  return __awaiter(this, void 0, void 0, function* () {
272
+ let rows = yield _request(_getObjectStore(this).get(key));
273
+ return new RowPacket(rows);
274
+ });
275
+ }
276
+ paginate() {
277
+ return __awaiter(this, arguments, void 0, function* (pageNo = 1, pageSize = 10, key, indexName) {
134
278
  const store = _getObjectStore(this);
135
- let cursor = yield _request(store.openCursor(key, direction));
136
- if (!cursor) {
137
- return [];
279
+ let request;
280
+ let count = pageSize * pageNo;
281
+ if (indexName) {
282
+ const index = store.index(indexName);
283
+ request = index.getAll(key, count);
138
284
  }
139
- let rows = [];
140
- while (cursor.value) {
141
- rows.push(cursor.value);
142
- cursor.continue();
285
+ else {
286
+ request = store.getAll(key, count);
143
287
  }
144
- return rows;
288
+ let rows = yield _request(request);
289
+ return new RowPacket(rows.slice(pageSize * (pageNo - 1), pageSize * pageNo));
145
290
  });
146
291
  }
147
- queryByIndex(indexName, key, count) {
148
- const store = _getObjectStore(this);
149
- const index = store.index(indexName);
150
- return _request(index.getAll(key || null, count));
151
- }
152
- deplete(key_1) {
153
- return __awaiter(this, arguments, void 0, function* (key, direction = 'next') {
154
- const store = _getObjectStore(this, 'readwrite');
155
- const cursor = yield _request(store.openCursor(key, direction));
156
- if (!cursor) {
157
- return [];
158
- }
159
- let rows = [];
160
- while (cursor.value) {
161
- rows.push(cursor.value);
162
- cursor.continue();
163
- }
164
- return rows;
292
+ queryById(id, indexName) {
293
+ return __awaiter(this, void 0, void 0, function* () {
294
+ const [result] = yield this.select(IDBKeyRange.only(id), 1, indexName);
295
+ return result;
165
296
  });
166
297
  }
167
- multiple(indexName_1, key_1) {
168
- return __awaiter(this, arguments, void 0, function* (indexName, key, direction = 'next') {
298
+ scan(key_1) {
299
+ return __awaiter(this, arguments, void 0, function* (key, direction = 'next', indexName) {
169
300
  const store = _getObjectStore(this);
170
- const index = store.index(indexName);
171
- const cursor = yield _request(index.openCursor(key, direction));
172
- if (!cursor) {
173
- return [];
301
+ let request;
302
+ if (!indexName) {
303
+ request = store.openCursor(key, direction);
174
304
  }
175
- let rows = [];
176
- while (cursor.value) {
177
- rows.push(cursor.value);
178
- cursor.continue();
305
+ else {
306
+ request = store.index(indexName).openCursor(key, direction);
179
307
  }
180
- return rows;
308
+ return new Promise((resolve, reject) => {
309
+ let packets = new RowPacket([]);
310
+ request.onsuccess = function (event) {
311
+ const req = event.target;
312
+ const cursor = req.result;
313
+ if (cursor) {
314
+ packets.push(cursor.value);
315
+ cursor.continue();
316
+ }
317
+ else {
318
+ resolve(packets);
319
+ }
320
+ };
321
+ request.onerror = function (event) {
322
+ reject(event);
323
+ };
324
+ });
325
+ });
326
+ }
327
+ getAllData() {
328
+ const store = _getObjectStore(this);
329
+ return _request(store.getAll());
330
+ }
331
+ getPagination() {
332
+ return __awaiter(this, arguments, void 0, function* (pageSize = 10, pageIndex = 1) {
333
+ const rows = yield this.getAllData();
334
+ return new Pagination(rows, pageSize, pageIndex);
181
335
  });
182
336
  }
183
337
  }
@@ -1 +1 @@
1
- {"root":["../src/com.ts","../src/const.ts","../src/database.ts","../src/driver.ts","../src/index.ts","../src/table.ts"],"version":"5.9.3"}
1
+ {"root":["../src/com.ts","../src/connection.ts","../src/const.ts","../src/database.ts","../src/index.ts","../src/table.ts"],"version":"5.9.3"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xdriver",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
4
4
  "description": "A simple driver for IndexDB",
5
5
  "main": "./lib/index",
6
6
  "files": [
package/lib/driver.d.ts DELETED
@@ -1,14 +0,0 @@
1
- import Database from "./database";
2
- import { Row, Rows } from "./table";
3
- export default class Driver extends Database {
4
- insert(table: string, data: Array<Record<string, any>>): Promise<any[]> | undefined;
5
- query(table: string, query?: IDBValidKey | IDBKeyRange, count?: number): Promise<Rows> | undefined;
6
- select(table: string, key?: IDBValidKey | IDBKeyRange, index?: string, count?: number): Promise<Rows> | undefined;
7
- selectByKey(table: string, key: IDBValidKey | IDBKeyRange): Promise<Row> | undefined;
8
- count(table: string, key: IDBValidKey | IDBKeyRange): Promise<number> | undefined;
9
- update(table: string, modify: Row, key?: IDBValidKey | IDBKeyRange | null, count?: number): Promise<IDBValidKey> | undefined;
10
- merge(table: string, row: Row | Rows): Promise<IDBValidKey> | Promise<any[]> | undefined;
11
- delete(table: string, key: IDBValidKey | IDBKeyRange): Promise<any[]> | undefined;
12
- truncate(table: string): Promise<undefined> | undefined;
13
- static connect(database: string, version: number | undefined, initialize: (driver: Driver) => void): Promise<Driver>;
14
- }
package/lib/driver.js DELETED
@@ -1,59 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import Database from "./database";
11
- export default class Driver extends Database {
12
- insert(table, data) {
13
- var _a;
14
- return (_a = this.table(table)) === null || _a === void 0 ? void 0 : _a.insert(data);
15
- }
16
- query(table, query, count = 1000) {
17
- var _a;
18
- return (_a = this.table(table)) === null || _a === void 0 ? void 0 : _a.query(query, count);
19
- }
20
- select(table, key, index, count = 1000) {
21
- var _a;
22
- return (_a = this.table(table)) === null || _a === void 0 ? void 0 : _a.select(key, count, index);
23
- }
24
- selectByKey(table, key) {
25
- var _a;
26
- return (_a = this.table(table)) === null || _a === void 0 ? void 0 : _a.queryByKey(key);
27
- }
28
- count(table, key) {
29
- var _a;
30
- return (_a = this.table(table)) === null || _a === void 0 ? void 0 : _a.count(key);
31
- }
32
- update(table, modify, key, count) {
33
- var _a;
34
- return (_a = this.table(table)) === null || _a === void 0 ? void 0 : _a.update(modify, key, count);
35
- }
36
- merge(table, row) {
37
- var _a;
38
- return (_a = this.table(table)) === null || _a === void 0 ? void 0 : _a.merge(row);
39
- }
40
- delete(table, key) {
41
- var _a;
42
- return (_a = this.table(table)) === null || _a === void 0 ? void 0 : _a.delete(key);
43
- }
44
- truncate(table) {
45
- var _a;
46
- return (_a = this.table(table)) === null || _a === void 0 ? void 0 : _a.clear();
47
- }
48
- static connect(database_1) {
49
- return __awaiter(this, arguments, void 0, function* (database, version = 1, initialize) {
50
- const driver = new Driver(database, version);
51
- driver.on('change', () => {
52
- initialize(driver);
53
- });
54
- yield driver.connect();
55
- return driver;
56
- });
57
- }
58
- ;
59
- }