chain-db-ts 0.0.2 → 1.0.0-rc.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.
Files changed (39) hide show
  1. package/CHANGELOG.md +110 -0
  2. package/dist/cjs/features/chain-db.d.ts +23 -64
  3. package/dist/cjs/features/chain-db.js +100 -263
  4. package/dist/cjs/features/constants.d.ts +11 -11
  5. package/dist/cjs/features/constants.js +22 -12
  6. package/dist/cjs/features/events.d.ts +28 -0
  7. package/dist/cjs/features/events.js +89 -0
  8. package/dist/cjs/features/table-doc.d.ts +37 -0
  9. package/dist/cjs/features/table-doc.js +135 -0
  10. package/dist/cjs/features/table.d.ts +81 -9
  11. package/dist/cjs/features/table.js +226 -70
  12. package/dist/cjs/features/types.d.ts +79 -21
  13. package/dist/cjs/features/types.js +30 -8
  14. package/dist/cjs/features/utils.d.ts +2 -1
  15. package/dist/cjs/features/utils.js +5 -2
  16. package/dist/cjs/index.d.ts +3 -2
  17. package/dist/cjs/index.js +8 -3
  18. package/features/chain-db.d.ts +23 -64
  19. package/features/chain-db.js +101 -241
  20. package/features/constants.d.ts +11 -11
  21. package/features/constants.js +14 -11
  22. package/features/events.d.ts +28 -0
  23. package/features/events.js +84 -0
  24. package/features/table-doc.d.ts +37 -0
  25. package/features/table-doc.js +129 -0
  26. package/features/table.d.ts +81 -9
  27. package/features/table.js +227 -69
  28. package/features/types.d.ts +79 -21
  29. package/features/types.js +29 -7
  30. package/features/utils.d.ts +2 -1
  31. package/features/utils.js +5 -2
  32. package/index.d.ts +3 -2
  33. package/index.js +3 -1
  34. package/package.json +5 -3
  35. package/readme.md +260 -132
  36. package/dist/cjs/features/access.d.ts +0 -6
  37. package/dist/cjs/features/access.js +0 -22
  38. package/features/access.d.ts +0 -6
  39. package/features/access.js +0 -16
@@ -1,15 +1,25 @@
1
1
  "use strict";
2
2
  exports.__esModule = true;
3
- exports.CHECK_USER_NAME = exports.GET_ALL_TRANSFER_BY_USER_ID = exports.GET_TRANSFER_BY_USER_ID = exports.TRANSFER_UNITS = exports.GET_USER_ACCOUNT_BY_ID = exports.GET_USER_ACCOUNT = exports.CREATE_USER_ACCOUNT = exports.CONTRACT_TRANSACTION = exports.CONTRACT_TRANSACTIONS_PAYLOAD = exports.CONTRACT_PAYLOAD = exports.API = void 0;
3
+ exports.WEB_SOCKET_EVENTS = exports.GET_DOC = exports.FIND_WHERE_ADVANCED = exports.FIND_WHERE_BASIC = exports.GET_HISTORY = exports.PERSIST_NEW_DATA = exports.UPDATE_ITEM = exports.GET_TABLE = exports.CONNECT = exports.API_BASE = exports.DEFAULT_API_SERVER = void 0;
4
4
  // Contants
5
- exports.API = 'http://localhost:2818';
6
- exports.CONTRACT_PAYLOAD = '/get_last_contract_transaction';
7
- exports.CONTRACT_TRANSACTIONS_PAYLOAD = '/get_contract_transactions';
8
- exports.CONTRACT_TRANSACTION = '/post_contract_transaction';
9
- exports.CREATE_USER_ACCOUNT = '/create_user_account';
10
- exports.GET_USER_ACCOUNT = '/get_user_account';
11
- exports.GET_USER_ACCOUNT_BY_ID = '/get_user_account_by_id';
12
- exports.TRANSFER_UNITS = '/transfer_units';
13
- exports.GET_TRANSFER_BY_USER_ID = '/get_transfer_by_user_id';
14
- exports.GET_ALL_TRANSFER_BY_USER_ID = '/get_all_transfers_by_user_id';
15
- exports.CHECK_USER_NAME = '/check_user_name';
5
+ exports.DEFAULT_API_SERVER = 'http://localhost:2818';
6
+ exports.API_BASE = '/api/v1';
7
+ exports.CONNECT = "".concat(exports.API_BASE, "/database/connect");
8
+ var GET_TABLE = function (table) { return "".concat(exports.API_BASE, "/table/").concat(table); };
9
+ exports.GET_TABLE = GET_TABLE;
10
+ var UPDATE_ITEM = function (table) { return "".concat(exports.API_BASE, "/table/").concat(table, "/update"); };
11
+ exports.UPDATE_ITEM = UPDATE_ITEM;
12
+ var PERSIST_NEW_DATA = function (table) { return "".concat(exports.API_BASE, "/table/").concat(table, "/persist"); };
13
+ exports.PERSIST_NEW_DATA = PERSIST_NEW_DATA;
14
+ var GET_HISTORY = function (table, limit) {
15
+ if (limit === void 0) { limit = 25; }
16
+ return "".concat(exports.API_BASE, "/table/").concat(table, "/history?limit=").concat(limit);
17
+ };
18
+ exports.GET_HISTORY = GET_HISTORY;
19
+ var FIND_WHERE_BASIC = function (table) { return "".concat(exports.API_BASE, "/table/").concat(table, "/find"); };
20
+ exports.FIND_WHERE_BASIC = FIND_WHERE_BASIC;
21
+ var FIND_WHERE_ADVANCED = function (table) { return "".concat(exports.API_BASE, "/table/").concat(table, "/find-advanced"); };
22
+ exports.FIND_WHERE_ADVANCED = FIND_WHERE_ADVANCED;
23
+ var GET_DOC = function (table, doc_id) { return "".concat(exports.API_BASE, "/table/").concat(table, "/doc/").concat(doc_id); };
24
+ exports.GET_DOC = GET_DOC;
25
+ exports.WEB_SOCKET_EVENTS = "".concat(exports.API_BASE, "/events");
@@ -0,0 +1,28 @@
1
+ type EventCallback = (data: any) => void;
2
+ declare class Events {
3
+ private socket;
4
+ private eventListeners;
5
+ private connected;
6
+ constructor(url: string, auth: string);
7
+ /**
8
+ * Subscribe to an event
9
+ * @param event Event name to subscribe to
10
+ * @param callback Function to call when the event is received
11
+ */
12
+ subscribe(event: string, callback: EventCallback): void;
13
+ /**
14
+ * Unsubscribe from an event
15
+ * @param event Event name to unsubscribe from
16
+ * @param callback Optional callback to remove. If not provided, all callbacks for the event will be removed.
17
+ */
18
+ unsubscribe(event: string, callback?: EventCallback): void;
19
+ /**
20
+ * Close the WebSocket connection
21
+ */
22
+ close(): void;
23
+ /**
24
+ * Check if the WebSocket connection is established
25
+ */
26
+ isConnected(): boolean;
27
+ }
28
+ export default Events;
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ exports.__esModule = true;
6
+ var ws_1 = __importDefault(require("ws"));
7
+ var Events = /** @class */ (function () {
8
+ function Events(url, auth) {
9
+ var _this = this;
10
+ this.eventListeners = new Map();
11
+ this.connected = false;
12
+ this.socket = new ws_1["default"](url, {
13
+ headers: {
14
+ Authorization: "Basic ".concat(auth)
15
+ }
16
+ });
17
+ //
18
+ this.socket.onopen = function () {
19
+ _this.connected = true;
20
+ console.log('ChainDB: WebSocket connection established');
21
+ };
22
+ this.socket.on('message', function (data) {
23
+ try {
24
+ var parsedData_1 = JSON.parse(data.toString());
25
+ if (parsedData_1.event_type && _this.eventListeners.has(parsedData_1.event_type)) {
26
+ var listeners = _this.eventListeners.get(parsedData_1.event_type) || [];
27
+ listeners.forEach(function (callback) { return callback(parsedData_1); });
28
+ }
29
+ }
30
+ catch (error) {
31
+ console.error('Error parsing WebSocket message:', error);
32
+ }
33
+ });
34
+ this.socket.on('close', function () {
35
+ _this.connected = false;
36
+ console.log('ChainDB: WebSocket connection closed');
37
+ });
38
+ this.socket.on('error', function (error) {
39
+ console.error('WebSocket error:', error);
40
+ });
41
+ }
42
+ /**
43
+ * Subscribe to an event
44
+ * @param event Event name to subscribe to
45
+ * @param callback Function to call when the event is received
46
+ */
47
+ Events.prototype.subscribe = function (event, callback) {
48
+ if (!this.eventListeners.has(event)) {
49
+ this.eventListeners.set(event, []);
50
+ }
51
+ var listeners = this.eventListeners.get(event) || [];
52
+ listeners.push(callback);
53
+ this.eventListeners.set(event, listeners);
54
+ };
55
+ /**
56
+ * Unsubscribe from an event
57
+ * @param event Event name to unsubscribe from
58
+ * @param callback Optional callback to remove. If not provided, all callbacks for the event will be removed.
59
+ */
60
+ Events.prototype.unsubscribe = function (event, callback) {
61
+ if (!this.eventListeners.has(event)) {
62
+ return;
63
+ }
64
+ if (callback) {
65
+ // Remove specific callback
66
+ var listeners = this.eventListeners.get(event) || [];
67
+ var updatedListeners = listeners.filter(function (cb) { return cb !== callback; });
68
+ this.eventListeners.set(event, updatedListeners);
69
+ }
70
+ else {
71
+ // Remove all callbacks for this event
72
+ this.eventListeners["delete"](event);
73
+ }
74
+ };
75
+ /**
76
+ * Close the WebSocket connection
77
+ */
78
+ Events.prototype.close = function () {
79
+ this.socket.close();
80
+ };
81
+ /**
82
+ * Check if the WebSocket connection is established
83
+ */
84
+ Events.prototype.isConnected = function () {
85
+ return this.connected;
86
+ };
87
+ return Events;
88
+ }());
89
+ exports["default"] = Events;
@@ -0,0 +1,37 @@
1
+ import { ChainDB } from './chain-db';
2
+ import { DocId, TableDoc } from './types';
3
+ /**
4
+ * Implementation of TableDoc interface
5
+ * Represents a specific document from a table
6
+ */
7
+ export declare class TableDocImpl<Model> implements TableDoc<Model> {
8
+ /**
9
+ * The document data
10
+ */
11
+ doc: DocId<Model>;
12
+ /**
13
+ * The document ID
14
+ */
15
+ private doc_id;
16
+ private tableName;
17
+ private db;
18
+ constructor(tableName: string, doc_id: string, data: DocId<Model>, db: ChainDB);
19
+ /**
20
+ * Update the document data
21
+ * This will update the specific document without creating a new one
22
+ */
23
+ update(): Promise<void>;
24
+ /**
25
+ * Refetch the document data from the database
26
+ * Useful when the document might have been updated by another application
27
+ */
28
+ refetch(): Promise<void>;
29
+ /**
30
+ * Get the table name this document belongs to
31
+ */
32
+ getTableName(): string;
33
+ /**
34
+ * Check if the table is empty
35
+ */
36
+ isEmpty(): boolean;
37
+ }
@@ -0,0 +1,135 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ exports.__esModule = true;
42
+ exports.TableDocImpl = void 0;
43
+ var axios_1 = __importDefault(require("axios"));
44
+ var constants_1 = require("./constants");
45
+ var utils_1 = require("./utils");
46
+ /**
47
+ * Implementation of TableDoc interface
48
+ * Represents a specific document from a table
49
+ */
50
+ var TableDocImpl = /** @class */ (function () {
51
+ function TableDocImpl(tableName, doc_id, data, db) {
52
+ this.tableName = tableName;
53
+ this.doc_id = doc_id;
54
+ this.doc = data;
55
+ this.db = db;
56
+ }
57
+ /**
58
+ * Update the document data
59
+ * This will update the specific document without creating a new one
60
+ */
61
+ TableDocImpl.prototype.update = function () {
62
+ return __awaiter(this, void 0, void 0, function () {
63
+ var url, body, response, e_1;
64
+ return __generator(this, function (_a) {
65
+ switch (_a.label) {
66
+ case 0:
67
+ url = "".concat(this.db.server).concat((0, constants_1.UPDATE_ITEM)(this.tableName));
68
+ body = {
69
+ data: this.doc,
70
+ doc_id: this.doc_id
71
+ };
72
+ _a.label = 1;
73
+ case 1:
74
+ _a.trys.push([1, 3, , 4]);
75
+ return [4 /*yield*/, (0, utils_1.post)(url, body, this.db.auth)];
76
+ case 2:
77
+ response = _a.sent();
78
+ if (!response.data.success) {
79
+ throw new Error(response.data.message);
80
+ }
81
+ return [3 /*break*/, 4];
82
+ case 3:
83
+ e_1 = _a.sent();
84
+ throw new Error("Something went wrong updating document ".concat(this.doc_id, ": ").concat(e_1.message || String(e_1)));
85
+ case 4: return [2 /*return*/];
86
+ }
87
+ });
88
+ });
89
+ };
90
+ /**
91
+ * Refetch the document data from the database
92
+ * Useful when the document might have been updated by another application
93
+ */
94
+ TableDocImpl.prototype.refetch = function () {
95
+ return __awaiter(this, void 0, void 0, function () {
96
+ var url, response, e_2;
97
+ return __generator(this, function (_a) {
98
+ switch (_a.label) {
99
+ case 0:
100
+ url = "".concat(this.db.server).concat((0, constants_1.GET_DOC)(this.tableName, this.doc_id));
101
+ _a.label = 1;
102
+ case 1:
103
+ _a.trys.push([1, 3, , 4]);
104
+ return [4 /*yield*/, axios_1["default"].get(url, { headers: { Authorization: "Basic ".concat(this.db.auth) } })];
105
+ case 2:
106
+ response = _a.sent();
107
+ if (!response.data.success) {
108
+ throw new Error(response.data.message);
109
+ }
110
+ // Update the table data with the latest data from the database
111
+ this.doc = response.data.data;
112
+ return [3 /*break*/, 4];
113
+ case 3:
114
+ e_2 = _a.sent();
115
+ throw new Error("Something went wrong refetching document ".concat(this.doc_id, ": ").concat(e_2.message || String(e_2)));
116
+ case 4: return [2 /*return*/];
117
+ }
118
+ });
119
+ });
120
+ };
121
+ /**
122
+ * Get the table name this document belongs to
123
+ */
124
+ TableDocImpl.prototype.getTableName = function () {
125
+ return this.tableName;
126
+ };
127
+ /**
128
+ * Check if the table is empty
129
+ */
130
+ TableDocImpl.prototype.isEmpty = function () {
131
+ return Object.keys(this.doc).length === 0;
132
+ };
133
+ return TableDocImpl;
134
+ }());
135
+ exports.TableDocImpl = TableDocImpl;
@@ -1,19 +1,91 @@
1
1
  import { ChainDB } from './chain-db';
2
+ import { Criteria, CriteriaAdvanced, DocId, TableDoc } from './types';
2
3
  declare class Table<Model> {
3
- table: Model;
4
- private contract_id;
4
+ currentDoc: Model;
5
+ private name;
5
6
  private db;
6
- constructor(table: Model, contract_id: string, db: ChainDB);
7
+ constructor(name: string, db: ChainDB);
7
8
  /**
8
- * Persist table data on chain
9
+ * Persist table's document data changes
9
10
  */
10
- persist(): Promise<void>;
11
+ persist(): Promise<DocId<Model>>;
11
12
  /**
12
13
  * Get the history of changes. A list of transactions from the most recent to the most old
13
14
  * in a range of depth
14
- * @param depth
15
+ * @param limit
15
16
  */
16
- getHistory(depth: number): Promise<Model[]>;
17
+ getHistory(limit: number): Promise<DocId<Model>[]>;
18
+ /**
19
+ * Refetch the table data
20
+ */
21
+ refetch(): Promise<void>;
22
+ /**
23
+ * Check if the table is empty
24
+ */
25
+ isEmpty(): boolean;
26
+ /**
27
+ * Get the table's name
28
+ */
29
+ getName(): string;
30
+ /**
31
+ * Find items in the table using basic criteria with exact matches
32
+ * @param criteria Object with fields and values to match exactly, e.g.: {age: 44, name: "john"}
33
+ * @param limit Maximum number of items to return (default: 1000)
34
+ * @param reverse If true, returns items in reverse order (default: true)
35
+ * @returns Array of found items matching the criteria
36
+ * @example
37
+ * // Find items where age is 44
38
+ * table.findWhere({
39
+ * age: 44,
40
+ * })
41
+ *
42
+ * // Find items with multiple criteria
43
+ * table.findWhere({
44
+ * age: 44,
45
+ * name: "john",
46
+ * active: true,
47
+ * score: 100
48
+ * })
49
+ */
50
+ findWhere(criteria: Criteria<Model>, limit?: number, reverse?: boolean): Promise<DocId<Model>[]>;
51
+ /**
52
+ * Find items in the table using advanced criteria with operators
53
+ * @param criteria Array of criteria to filter items. Each criteria contains:
54
+ * - field: The field name to filter
55
+ * - operator: The operator to use in comparison. Available operators:
56
+ * - Eq (==) Equal
57
+ * - Ne (!=) Not Equal
58
+ * - Gt (>) Greater Than
59
+ * - Ge (>=) Greater Than or Equal
60
+ * - Lt (<) Less Than
61
+ * - Le (<=) Less Than or Equal
62
+ * - Contains: Check if field contains value (for strings and arrays)
63
+ * - StartsWith: Check if field starts with value (for strings)
64
+ * - EndsWith: Check if field ends with value (for strings)
65
+ * - value: The value to compare against
66
+ * @param limit Maximum number of items to return (default: 1000)
67
+ * @param reverse If true, returns items in reverse order (default: true)
68
+ * @returns Array of found items matching the criteria
69
+ * @example
70
+ * // Find items where greeting contains "arg"
71
+ * table.findWhereAdvanced([
72
+ * {
73
+ * field: "greeting",
74
+ * operator: Operators.Contains,
75
+ * value: "hello"
76
+ * }
77
+ * ])
78
+ */
79
+ findWhereAdvanced(criteria: CriteriaAdvanced<Model>[], limit?: number, reverse?: boolean): Promise<DocId<Model>[]>;
80
+ /**
81
+ * Get the current document ID
82
+ */
83
+ getCurrentDocId(): string;
84
+ /**
85
+ * Get a specific document by its ID
86
+ * @param doc_id The document ID to retrieve
87
+ * @returns A TableDoc instance with the specific document data
88
+ */
89
+ getDoc(doc_id: string): Promise<TableDoc<Model>>;
17
90
  }
18
- export declare const get: <Model>(db: ChainDB, table_name: string, model: Model) => Promise<Table<Model>>;
19
- export {};
91
+ export default Table;