prostgles-client 4.0.358 → 4.0.360

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.
@@ -0,0 +1,146 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createSyncStateUtils = void 0;
4
+ const prostgles_types_1 = require("prostgles-types");
5
+ const createSyncStateUtils = (socket, options) => {
6
+ const state = { isSynced: false };
7
+ const { db, name, select = "*", filter = {}, columns } = options;
8
+ const channelName = (0, prostgles_types_1.getSyncChannelName)({ filter, select, tableName: name });
9
+ const onDebug = (evt) => {
10
+ var _a;
11
+ return (_a = options.onDebug) === null || _a === void 0 ? void 0 : _a.call(options, {
12
+ ...evt,
13
+ type: "sync",
14
+ tableName: name,
15
+ channelName,
16
+ options,
17
+ });
18
+ };
19
+ onDebug({ command: "create", data: { name, filter, select } });
20
+ const tableHandler = db[name];
21
+ if (!tableHandler) {
22
+ throw `${name} table not found in db`;
23
+ }
24
+ const { _syncInfo } = tableHandler;
25
+ if (!_syncInfo) {
26
+ throw `${name} table does not support sync`;
27
+ }
28
+ const { id_fields, synced_field, throttle = 100, batch_size = 50 } = _syncInfo;
29
+ if (!id_fields.length || !synced_field) {
30
+ throw "id_fields/synced_field missing";
31
+ }
32
+ const _sync = async (handles) => {
33
+ const sync_info = await new Promise((resolve, reject) => {
34
+ socket.emit(prostgles_types_1.CHANNEL_PREFIX, {
35
+ tableName: name,
36
+ command: "sync",
37
+ param1: filter,
38
+ param2: { select },
39
+ }, (err, syncInfo) => {
40
+ if (err) {
41
+ console.error(err);
42
+ reject(err);
43
+ }
44
+ else if (syncInfo) {
45
+ const { id_fields, synced_field, channelName } = syncInfo;
46
+ socket.emit(channelName, { onSyncRequest: handles.onSyncRequest({}) }, (response) => {
47
+ console.log(response);
48
+ });
49
+ resolve({ id_fields, synced_field, channelName });
50
+ }
51
+ });
52
+ });
53
+ const onCall = function (data, cb) {
54
+ /*
55
+ Client will:
56
+ 1. Send last_synced on(onSyncRequest)
57
+ 2. Send data >= server_synced on(onPullRequest)
58
+ 3. Send data on CRUD emit(data.data)
59
+ 4. Upsert data.data on(data.data)
60
+ */
61
+ if (!data)
62
+ return;
63
+ const { onUpdates, onSyncRequest, onPullRequest } = handles;
64
+ // syncedTables.get(channelName)?.then((syncedTable) => {
65
+ // onDebug?.({
66
+ // type: "sync",
67
+ // command:
68
+ // data.data ? "onUpdates"
69
+ // : data.onSyncRequest ? "onSyncRequest"
70
+ // : "onPullRequest",
71
+ // tableName,
72
+ // channelName,
73
+ // data,
74
+ // options: { n filter, select },
75
+ // });
76
+ // });
77
+ if (data.data) {
78
+ Promise.resolve(onUpdates(data))
79
+ .then(() => {
80
+ cb({ ok: true });
81
+ })
82
+ .catch((err) => {
83
+ cb({ err });
84
+ });
85
+ }
86
+ else if (data.onSyncRequest) {
87
+ Promise.resolve(onSyncRequest(data.onSyncRequest))
88
+ .then((res) => cb({ onSyncRequest: res }))
89
+ .catch((err) => {
90
+ cb({ err });
91
+ });
92
+ }
93
+ else if (data.onPullRequest) {
94
+ Promise.resolve(onPullRequest(data.onPullRequest))
95
+ .then((result) => {
96
+ cb(result);
97
+ })
98
+ .catch((err) => {
99
+ cb({ err });
100
+ });
101
+ }
102
+ else {
103
+ console.log("unexpected response");
104
+ }
105
+ };
106
+ socket.on(channelName, onCall);
107
+ const syncData = function (data, deleted, cb) {
108
+ socket.emit(channelName, {
109
+ onSyncRequest: {
110
+ ...handles.onSyncRequest({}),
111
+ ...{ data },
112
+ ...{ deleted },
113
+ },
114
+ }, !cb ? null : ((response) => {
115
+ cb(response);
116
+ }));
117
+ };
118
+ const unsync = () => {
119
+ return new Promise((resolve, reject) => {
120
+ socket.emit(channelName + "unsync", {}, (err, res) => {
121
+ if (err)
122
+ reject(err);
123
+ else
124
+ resolve(res);
125
+ });
126
+ socket.removeListener(channelName, onCall);
127
+ });
128
+ };
129
+ return { sync_info, unsync, syncData };
130
+ };
131
+ return {
132
+ state,
133
+ onDebug,
134
+ id_fields,
135
+ synced_field,
136
+ throttle,
137
+ batch_size,
138
+ columns,
139
+ _syncInfo,
140
+ _sync,
141
+ filter,
142
+ select,
143
+ tableHandler,
144
+ };
145
+ };
146
+ exports.createSyncStateUtils = createSyncStateUtils;
@@ -0,0 +1,11 @@
1
+ import type { AnyObject, SyncConfig } from "prostgles-types";
2
+ import { WAL } from "prostgles-types/dist/WAL";
3
+ import type { createSyncDataStore } from "./createSyncDataStore";
4
+ import type { createSyncStateUtils } from "./createSyncStateUtils";
5
+ import type { ItemUpdate, MultiChangeListener, MultiSyncHandles, SingleChangeListener, SingleSyncHandles } from "./SyncedTable";
6
+ export declare const createSyncSubscriptionManager: ({ id_fields, synced_field }: Omit<SyncConfig, "channelName">, store: ReturnType<typeof createSyncDataStore>, stateUtils: ReturnType<typeof createSyncStateUtils>, upsert: (items: ItemUpdate[], from_server?: boolean) => Promise<void>) => {
7
+ sync: <T extends AnyObject = AnyObject>(onChange: MultiChangeListener<T>, handlesOnData?: boolean) => MultiSyncHandles<T>;
8
+ syncOne: <T extends AnyObject = AnyObject, Full extends boolean = false>(idObj: Partial<T>, onChange: SingleChangeListener<T, Full>, handlesOnData?: boolean) => SingleSyncHandles<T, Full>;
9
+ notifyWal: WAL;
10
+ };
11
+ //# sourceMappingURL=createSyncSubscriptionManager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createSyncSubscriptionManager.d.ts","sourceRoot":"","sources":["../../lib/SyncedTable/createSyncSubscriptionManager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAiB,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC5E,OAAO,EAAE,GAAG,EAAE,MAAM,0BAA0B,CAAC;AAC/C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,KAAK,EAEV,UAAU,EAEV,mBAAmB,EACnB,gBAAgB,EAChB,oBAAoB,EACpB,iBAAiB,EAIlB,MAAM,eAAe,CAAC;AAEvB,eAAO,MAAM,6BAA6B,GACxC,6BAA6B,IAAI,CAAC,UAAU,EAAE,aAAa,CAAC,EAC5D,OAAO,UAAU,CAAC,OAAO,mBAAmB,CAAC,EAC7C,YAAY,UAAU,CAAC,OAAO,oBAAoB,CAAC,EACnD,QAAQ,CAAC,KAAK,EAAE,UAAU,EAAE,EAAE,WAAW,CAAC,EAAE,OAAO,KAAK,OAAO,CAAC,IAAI,CAAC;WAgKvD,CAAC,SAAS,SAAS,wBACrB,mBAAmB,CAAC,CAAC,CAAC,8BAE/B,gBAAgB,CAAC,CAAC,CAAC;cAsDL,CAAC,SAAS,SAAS,cAAc,IAAI,SAAS,OAAO,iBAC7D,OAAO,CAAC,CAAC,CAAC,YACP,oBAAoB,CAAC,CAAC,EAAE,IAAI,CAAC,8BAEtC,iBAAiB,CAAC,CAAC,EAAE,IAAI,CAAC;;CAuC9B,CAAC"}
@@ -0,0 +1,230 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createSyncSubscriptionManager = void 0;
4
+ const WAL_1 = require("prostgles-types/dist/WAL");
5
+ const createSyncSubscriptionManager = ({ id_fields, synced_field }, store, stateUtils, upsert) => {
6
+ let multiSubscriptions = [];
7
+ let singleSubscriptions = [];
8
+ const unsubscribe = (onChange) => {
9
+ singleSubscriptions = singleSubscriptions.filter((s) => s._onChange !== onChange);
10
+ multiSubscriptions = multiSubscriptions.filter((s) => s._onChange !== onChange);
11
+ return "ok";
12
+ };
13
+ const { state, onDebug } = stateUtils;
14
+ /**
15
+ * Notifies multi subs with ALL data + deltas. Attaches handles on data if required
16
+ * @param newData -> updates. Must include id_fields + updates
17
+ */
18
+ const _notifySubscribers = (changes = []) => {
19
+ if (!state.isSynced) {
20
+ onDebug({ command: "notifySubscribers", data: [], info: "not synced yet" });
21
+ return;
22
+ }
23
+ else {
24
+ onDebug({ command: "notifySubscribers", data: changes });
25
+ }
26
+ /* Deleted items (changes = []) do not trigger singleSubscriptions notify because it might break things */
27
+ const items = [], deltas = [], ids = [];
28
+ changes.map(({ idObj, newItem, delta }) => {
29
+ /* Single subs do not care about the filter */
30
+ singleSubscriptions
31
+ .filter((s) => store.matchesIdObj(s.idObj, idObj))
32
+ .map(async (s) => {
33
+ try {
34
+ await s.notify(newItem, delta);
35
+ }
36
+ catch (e) {
37
+ console.error("SyncedTable failed to notify: ", e);
38
+ }
39
+ });
40
+ /* Preparing data for multi subs */
41
+ if (store.matchesFilter(newItem)) {
42
+ items.push(newItem);
43
+ deltas.push(delta);
44
+ ids.push(idObj);
45
+ }
46
+ });
47
+ if (multiSubscriptions.length) {
48
+ const allItems = [], allDeltas = [];
49
+ store.getItems().map((d) => {
50
+ allItems.push({ ...d });
51
+ const dIdx = items.findIndex((_d) => store.matchesIdObj(d, _d));
52
+ allDeltas.push(deltas[dIdx]);
53
+ });
54
+ /* Multisubs must not forget about the original filter */
55
+ multiSubscriptions.map(async (s) => {
56
+ try {
57
+ await s.notify(allItems, allDeltas);
58
+ }
59
+ catch (e) {
60
+ console.error("SyncedTable failed to notify: ", e);
61
+ }
62
+ });
63
+ }
64
+ };
65
+ const notifyWal = new WAL_1.WAL({
66
+ id_fields,
67
+ synced_field,
68
+ batch_size: Infinity,
69
+ throttle: 5,
70
+ onSend: async (_, fullItems) => {
71
+ _notifySubscribers(fullItems.map((d) => {
72
+ var _a;
73
+ return ({
74
+ delta: store.getDelta((_a = d.initial) !== null && _a !== void 0 ? _a : {}, d.current),
75
+ idObj: store.getIdObj(d.current),
76
+ newItem: d.current,
77
+ });
78
+ }));
79
+ },
80
+ });
81
+ const _delete = async (item, from_server = false) => {
82
+ var _a, _b;
83
+ const idObj = store.getIdObj(item);
84
+ store.setItem(idObj, true, true);
85
+ if (!from_server) {
86
+ await ((_b = (_a = stateUtils.tableHandler).delete) === null || _b === void 0 ? void 0 : _b.call(_a, idObj));
87
+ }
88
+ _notifySubscribers();
89
+ return true;
90
+ };
91
+ const getMultiSyncSubscription = ({ onChange, handlesOnData, }) => {
92
+ const handles = {
93
+ $unsync: () => {
94
+ return unsubscribe(onChange);
95
+ },
96
+ getItems: () => {
97
+ return store.getItems();
98
+ },
99
+ $upsert: (newData) => {
100
+ if (!newData) {
101
+ throw "No data provided for upsert";
102
+ }
103
+ const prepareOne = (d) => {
104
+ return {
105
+ idObj: store.getIdObj(d),
106
+ delta: d,
107
+ };
108
+ };
109
+ if (Array.isArray(newData)) {
110
+ upsert(newData.map((d) => prepareOne(d)));
111
+ }
112
+ else {
113
+ upsert([prepareOne(newData)]);
114
+ }
115
+ },
116
+ };
117
+ const sub = {
118
+ _onChange: onChange,
119
+ handlesOnData,
120
+ handles,
121
+ notify: (_allItems, _allDeltas) => {
122
+ let allItems = [..._allItems];
123
+ const allDeltas = [..._allDeltas];
124
+ if (handlesOnData) {
125
+ allItems = allItems.map((item, i) => {
126
+ const getItem = (d, idObj) => ({
127
+ ...d,
128
+ ...makeSingleSyncHandles(idObj, onChange),
129
+ $get: () => getItem(store.getItem(idObj), idObj),
130
+ $find: (idObject) => getItem(store.getItem(idObject), idObject),
131
+ $update: (newData, opts) => {
132
+ return upsert([{ idObj, delta: newData, opts }]);
133
+ },
134
+ $delete: async () => {
135
+ return _delete(idObj);
136
+ },
137
+ $cloneMultiSync: (onChange) => sync(onChange, handlesOnData),
138
+ });
139
+ const idObj = store.getIdObj(item);
140
+ return getItem(item, idObj);
141
+ });
142
+ }
143
+ return onChange(allItems, allDeltas);
144
+ },
145
+ };
146
+ return { sub, handles };
147
+ };
148
+ const sync = (onChange, handlesOnData = true) => {
149
+ const { sub, handles } = getMultiSyncSubscription.bind(this)({
150
+ onChange: onChange,
151
+ handlesOnData,
152
+ });
153
+ multiSubscriptions.push(sub);
154
+ setTimeout(() => {
155
+ const items = store.getItems();
156
+ sub.notify(items, items);
157
+ }, 0);
158
+ return Object.freeze({ ...handles });
159
+ };
160
+ const makeSingleSyncHandles = (idObj, onChange) => {
161
+ const handles = {
162
+ $get: () => store.getItem(idObj),
163
+ $find: (idObject) => store.getItem(idObject),
164
+ $unsync: () => {
165
+ return unsubscribe(onChange);
166
+ },
167
+ $delete: () => {
168
+ return _delete(idObj);
169
+ },
170
+ $update: (newData, opts) => {
171
+ /* DROPPED SYNC BUG */
172
+ if (!singleSubscriptions.length && !multiSubscriptions.length) {
173
+ console.warn("No sync listeners");
174
+ }
175
+ return upsert([{ idObj, delta: newData, opts }]);
176
+ },
177
+ $cloneSync: (onChange) => syncOne(idObj, onChange),
178
+ // TODO: add clone sync hook
179
+ // $useCloneSync: () => {
180
+ // const handles = this.syncOne<T, Full>(idObj, item => {
181
+ // setItem()
182
+ // });
183
+ // return handles.$unsync;
184
+ // },
185
+ $cloneMultiSync: (onChange) => sync(onChange, true),
186
+ };
187
+ return handles;
188
+ };
189
+ /**
190
+ * Returns a sync handler to a specific record within the SyncedTable instance
191
+ * @param idObj object containing the target id_fields properties
192
+ * @param onChange change listener <(item: object, delta: object) => any >
193
+ * @param handlesOnData If true then $update, $delete and $unsync handles will be added on the data item. True by default;
194
+ */
195
+ const syncOne = (idObj, onChange, handlesOnData = true) => {
196
+ const handles = makeSingleSyncHandles(idObj, onChange);
197
+ const sub = {
198
+ _onChange: onChange,
199
+ idObj,
200
+ handlesOnData,
201
+ handles,
202
+ notify: (data, delta) => {
203
+ const newData = { ...data };
204
+ if (handlesOnData) {
205
+ newData.$get = handles.$get;
206
+ newData.$find = handles.$find;
207
+ newData.$update = handles.$update;
208
+ newData.$delete = handles.$delete;
209
+ newData.$unsync = handles.$unsync;
210
+ newData.$cloneSync = handles.$cloneSync;
211
+ }
212
+ return onChange(newData, delta);
213
+ },
214
+ };
215
+ singleSubscriptions.push(sub);
216
+ setTimeout(() => {
217
+ const existingData = handles.$get();
218
+ if (existingData) {
219
+ sub.notify(existingData, existingData);
220
+ }
221
+ }, 0);
222
+ return Object.freeze({ ...handles });
223
+ };
224
+ return {
225
+ sync,
226
+ syncOne,
227
+ notifyWal,
228
+ };
229
+ };
230
+ exports.createSyncSubscriptionManager = createSyncSubscriptionManager;
@@ -3,15 +3,17 @@ import type { getSubscriptionHandler } from "./getSubscriptionHandler";
3
3
  import type { getSyncHandler } from "./getSyncHandler";
4
4
  import { type DBHandlerClient, type InitOptions } from "./prostgles";
5
5
  import { type SyncedTable } from "./SyncedTable/SyncedTable";
6
+ import type { getSyncHandlerV2 } from "./getSyncHandlerV2";
6
7
  type Args = {
7
8
  tableSchema: DBSchemaTable[] | undefined;
8
9
  onDebug: InitOptions["onDebug"];
9
10
  socket: InitOptions["socket"];
10
11
  syncedTable: typeof SyncedTable | undefined;
11
12
  syncHandler: ReturnType<typeof getSyncHandler>;
13
+ syncHandlerV2: ReturnType<typeof getSyncHandlerV2>;
12
14
  subscriptionHandler: ReturnType<typeof getSubscriptionHandler>;
13
15
  };
14
- export declare const getDB: <DBSchema = void>({ tableSchema, onDebug, syncedTable, syncHandler, subscriptionHandler, socket, }: Args) => {
16
+ export declare const getDB: <DBSchema = void>({ tableSchema, onDebug, syncedTable, syncHandler, syncHandlerV2, subscriptionHandler, socket, }: Args) => {
15
17
  db: Partial<DBHandlerClient<DBSchema>>;
16
18
  };
17
19
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"getDbHandler.d.ts","sourceRoot":"","sources":["../lib/getDbHandler.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,aAAa,EAKnB,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAIvD,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,WAAW,EAEjB,MAAM,aAAa,CAAC;AACrB,OAAO,EAKL,KAAK,WAAW,EAIjB,MAAM,2BAA2B,CAAC;AAEnC,KAAK,IAAI,GAAG;IACV,WAAW,EAAE,aAAa,EAAE,GAAG,SAAS,CAAC;IACzC,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;IAChC,MAAM,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;IAC9B,WAAW,EAAE,OAAO,WAAW,GAAG,SAAS,CAAC;IAC5C,WAAW,EAAE,UAAU,CAAC,OAAO,cAAc,CAAC,CAAC;IAC/C,mBAAmB,EAAE,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC;CAChE,CAAC;AAIF,eAAO,MAAM,KAAK,GAAI,QAAQ,GAAG,IAAI,EAAE,kFAOpC,IAAI;QA6Nc,OAAO,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC;CACtD,CAAC"}
1
+ {"version":3,"file":"getDbHandler.d.ts","sourceRoot":"","sources":["../lib/getDbHandler.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,aAAa,EAKnB,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AACvE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAIvD,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,WAAW,EAEjB,MAAM,aAAa,CAAC;AACrB,OAAO,EAKL,KAAK,WAAW,EAIjB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAE3D,KAAK,IAAI,GAAG;IACV,WAAW,EAAE,aAAa,EAAE,GAAG,SAAS,CAAC;IACzC,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;IAChC,MAAM,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;IAC9B,WAAW,EAAE,OAAO,WAAW,GAAG,SAAS,CAAC;IAC5C,WAAW,EAAE,UAAU,CAAC,OAAO,cAAc,CAAC,CAAC;IAC/C,aAAa,EAAE,UAAU,CAAC,OAAO,gBAAgB,CAAC,CAAC;IACnD,mBAAmB,EAAE,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC;CAChE,CAAC;AAIF,eAAO,MAAM,KAAK,GAAI,QAAQ,GAAG,IAAI,EAAE,iGAQpC,IAAI;QAyNc,OAAO,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC;CACtD,CAAC"}
@@ -7,7 +7,7 @@ const useSubscribe_1 = require("./hooks/useSubscribe");
7
7
  const useSync_1 = require("./hooks/useSync");
8
8
  const SyncedTable_1 = require("./SyncedTable/SyncedTable");
9
9
  const preffix = prostgles_types_1.CHANNELS._preffix;
10
- const getDB = ({ tableSchema, onDebug, syncedTable, syncHandler, subscriptionHandler, socket, }) => {
10
+ const getDB = ({ tableSchema, onDebug, syncedTable, syncHandler, syncHandlerV2, subscriptionHandler, socket, }) => {
11
11
  var _a;
12
12
  /* Building DB object */
13
13
  const checkSubscriptionArgs = (basicFilter, options, onChange, onError) => {
@@ -21,7 +21,7 @@ const getDB = ({ tableSchema, onDebug, syncedTable, syncHandler, subscriptionHan
21
21
  const subscribeCommands = ["subscribe", "subscribeOne"];
22
22
  const db = {};
23
23
  const schemaClone = (_a = (0, SyncedTable_1.quickClone)(tableSchema)) !== null && _a !== void 0 ? _a : [];
24
- schemaClone.forEach(({ name: tableName, publishInfo }) => {
24
+ schemaClone.forEach(({ name: tableName, publishInfo, columns }) => {
25
25
  const allowedCommands = (0, prostgles_types_1.getAllowedTableMethods)({ publishInfo });
26
26
  db[tableName] = {};
27
27
  const dboTable = db[tableName];
@@ -36,31 +36,18 @@ const getDB = ({ tableSchema, onDebug, syncedTable, syncHandler, subscriptionHan
36
36
  }
37
37
  dboTable._syncInfo = { ...syncConfig };
38
38
  if (syncedTable) {
39
- dboTable.getSync = async (filter, params = {}) => {
40
- await (onDebug === null || onDebug === void 0 ? void 0 : onDebug({
41
- type: "table",
42
- command: "getSync",
43
- tableName,
44
- data: { filter, params },
45
- }));
46
- return syncedTable.create({
47
- name: tableName,
48
- onDebug,
49
- filter,
50
- db: db,
51
- ...params,
52
- });
53
- };
54
39
  const upsertSyncTable = async (basicFilter = {}, options = {}, onError) => {
55
40
  var _a;
56
41
  const syncName = `${tableName}.${JSON.stringify(basicFilter)}.${JSON.stringify((0, prostgles_types_1.omitKeys)(options, ["handlesOnData"]))}`;
57
42
  const syncedTableHandler = (_a = syncHandler.syncedTables.get(syncName)) !== null && _a !== void 0 ? _a : syncedTable.create({
43
+ select: undefined,
58
44
  ...options,
59
45
  onDebug,
60
46
  name: tableName,
61
47
  filter: basicFilter,
62
48
  db: db,
63
49
  onError,
50
+ columns,
64
51
  });
65
52
  syncHandler.syncedTables.set(syncName, syncedTableHandler);
66
53
  return syncedTableHandler;
@@ -73,8 +60,9 @@ const getDB = ({ tableSchema, onDebug, syncedTable, syncHandler, subscriptionHan
73
60
  data: { basicFilter, options },
74
61
  }));
75
62
  checkSubscriptionArgs(basicFilter, options, onChange, onError);
76
- const s = await upsertSyncTable(basicFilter, options, onError);
77
- return await s.syncOne(basicFilter, onChange, options.handlesOnData);
63
+ // const syncedTable = await upsertSyncTable(basicFilter, options, onError);
64
+ // return await syncedTable.syncOne(basicFilter, onChange as any, options.handlesOnData);
65
+ return (await syncHandlerV2.getTableSyncFunctions({ db, tableName, columns })).addSyncOne(basicFilter, options, onChange, onError);
78
66
  });
79
67
  const sync = (async (basicFilter, options = { handlesOnData: true }, onChange, onError) => {
80
68
  await (onDebug === null || onDebug === void 0 ? void 0 : onDebug({
@@ -84,8 +72,9 @@ const getDB = ({ tableSchema, onDebug, syncedTable, syncHandler, subscriptionHan
84
72
  data: { basicFilter, options },
85
73
  }));
86
74
  checkSubscriptionArgs(basicFilter, options, onChange, onError);
87
- const s = await upsertSyncTable(basicFilter, options, onError);
88
- return await s.sync(onChange, options.handlesOnData);
75
+ // const syncedTable = await upsertSyncTable(basicFilter, options, onError);
76
+ // return await syncedTable.sync(onChange as any, options.handlesOnData);
77
+ return (await syncHandlerV2.getTableSyncFunctions({ db, tableName, columns })).addSync(basicFilter, options, onChange, onError);
89
78
  });
90
79
  dboTable.sync = sync;
91
80
  dboTable.syncOne = syncOne;
@@ -103,7 +92,7 @@ const getDB = ({ tableSchema, onDebug, syncedTable, syncHandler, subscriptionHan
103
92
  tableName,
104
93
  data: { filter, select, syncHandles },
105
94
  }));
106
- return syncHandler.addSync({ tableName, command, filter, select }, syncHandles);
95
+ return syncHandler.addSync({ tableName, command, param1: filter, param2: select }, syncHandles);
107
96
  };
108
97
  }
109
98
  else if (subscribeCommands.includes(command)) {
@@ -118,7 +107,7 @@ const getDB = ({ tableSchema, onDebug, syncedTable, syncHandler, subscriptionHan
118
107
  return subscriptionHandler.addSub(db, { tableName, command, param1, param2 }, onChange, onError);
119
108
  };
120
109
  dboTable[command] = subFunc;
121
- const SUBONE = "subscribeOne";
110
+ const SUBSCRIBE_ONE = "subscribeOne";
122
111
  /**
123
112
  * React hooks
124
113
  */
@@ -128,13 +117,13 @@ const getDB = ({ tableSchema, onDebug, syncedTable, syncHandler, subscriptionHan
128
117
  if (handlerName) {
129
118
  dboTable[handlerName] = (filter, options, hookOptions) =>
130
119
  // eslint-disable-next-line react-hooks/rules-of-hooks
131
- (0, useSubscribe_1.useSubscribe)(subFunc, command === SUBONE, filter, options, hookOptions);
120
+ (0, useSubscribe_1.useSubscribe)(subFunc, command === SUBSCRIBE_ONE, filter, options, hookOptions);
132
121
  }
133
- if (command === SUBONE || !subscribeCommands.includes(SUBONE)) {
134
- dboTable[SUBONE] = async function (param1, param2, onChange) {
122
+ if (command === SUBSCRIBE_ONE || !subscribeCommands.includes(SUBSCRIBE_ONE)) {
123
+ dboTable[SUBSCRIBE_ONE] = async function (param1, param2, onChange) {
135
124
  await (onDebug === null || onDebug === void 0 ? void 0 : onDebug({
136
125
  type: "table",
137
- command: "getSync",
126
+ command: SUBSCRIBE_ONE,
138
127
  tableName,
139
128
  data: { param1, param2, onChange },
140
129
  }));
@@ -1 +1 @@
1
- {"version":3,"file":"getSyncHandler.d.ts","sourceRoot":"","sources":["../lib/getSyncHandler.ts"],"names":[],"mappings":"AAAA,OAAO,EAA2B,KAAK,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAElF,OAAO,KAAK,EAA2B,WAAW,EAAY,UAAU,EAAE,MAAM,aAAa,CAAC;AAE9F,OAAO,KAAK,EAAe,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAQ1E,eAAO,MAAM,cAAc,GAAI,qBAAqB,IAAI,CAAC,WAAW,EAAE,QAAQ,GAAG,SAAS,CAAC;;;sBAoE1D,UAAU,YAAY,iBAAiB,KAAG,OAAO,CAAC,GAAG,CAAC;;CAiJtF,CAAC"}
1
+ {"version":3,"file":"getSyncHandler.d.ts","sourceRoot":"","sources":["../lib/getSyncHandler.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,iBAAiB,EAEvB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,KAAK,EAAe,WAAW,EAAY,UAAU,EAAE,MAAM,aAAa,CAAC;AAElF,OAAO,KAAK,EAAe,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAQ1E,eAAO,MAAM,cAAc,GAAI,qBAAqB,IAAI,CAAC,WAAW,EAAE,QAAQ,GAAG,SAAS,CAAC;;;sBA4E1D,UAAU,YAAY,iBAAiB,KAAG,OAAO,CAAC,GAAG,CAAC;;CAgJtF,CAAC"}
@@ -36,14 +36,19 @@ const getSyncHandler = ({ socket, onDebug }) => {
36
36
  }
37
37
  });
38
38
  }
39
- function addServerSync({ tableName, command, filter, select }, onSyncRequest) {
39
+ function addServerSync({ tableName, command, param1 = {}, param2 }, onSyncRequest) {
40
40
  return new Promise((resolve, reject) => {
41
- socket.emit(prostgles_types_1.CHANNEL_PREFIX, { tableName, command, param1: filter, param2: select }, (err, syncInfo) => {
41
+ socket.emit(prostgles_types_1.CHANNEL_PREFIX, {
42
+ tableName,
43
+ command,
44
+ param1,
45
+ param2,
46
+ }, (err, syncInfo) => {
42
47
  onDebug === null || onDebug === void 0 ? void 0 : onDebug({
43
48
  type: "table",
44
- command: "getSync",
49
+ command: "sync",
45
50
  tableName,
46
- data: { filter, select },
51
+ data: { param1, param2 },
47
52
  });
48
53
  if (err) {
49
54
  console.error(err);
@@ -63,7 +68,7 @@ const getSyncHandler = ({ socket, onDebug }) => {
63
68
  async function addSync(params, triggers) {
64
69
  return addSyncQueuer.run([params, triggers]);
65
70
  }
66
- async function _addSync({ tableName, command, filter, select }, clientSyncHandlers) {
71
+ async function _addSync({ tableName, command, param1, param2 }, clientSyncHandlers) {
67
72
  const { onSyncRequest } = clientSyncHandlers;
68
73
  function makeHandler(channelName) {
69
74
  const unsync = function () {
@@ -84,9 +89,8 @@ const getSyncHandler = ({ socket, onDebug }) => {
84
89
  }
85
90
  const matchingSync = Array.from(syncs.entries()).find(([ch, s]) => {
86
91
  return (s.tableName === tableName &&
87
- s.command === command &&
88
- (0, prostgles_types_1.isEqual)(s.filter, filter) &&
89
- (0, prostgles_types_1.isEqual)(s.select, select));
92
+ (0, prostgles_types_1.isEqual)(s.param1, param1) &&
93
+ (0, prostgles_types_1.isEqual)(s.param2.select, param2.select));
90
94
  });
91
95
  if (matchingSync) {
92
96
  const [existingChannel, existingSync] = matchingSync;
@@ -94,7 +98,7 @@ const getSyncHandler = ({ socket, onDebug }) => {
94
98
  return makeHandler(existingChannel);
95
99
  }
96
100
  else {
97
- const sync_info = await addServerSync({ tableName, command, filter, select }, onSyncRequest);
101
+ const sync_info = await addServerSync({ tableName, command, param1, param2 }, onSyncRequest);
98
102
  const { channelName } = sync_info;
99
103
  const onCall = function (data, cb) {
100
104
  /*
@@ -110,19 +114,19 @@ const getSyncHandler = ({ socket, onDebug }) => {
110
114
  if (!matchingSync)
111
115
  return;
112
116
  matchingSync.clientSyncHandles.map(({ onUpdates, onSyncRequest, onPullRequest }) => {
113
- var _a;
114
- (_a = syncedTables.get(channelName)) === null || _a === void 0 ? void 0 : _a.then((syncedTable) => {
115
- onDebug === null || onDebug === void 0 ? void 0 : onDebug({
116
- type: "sync",
117
- command: data.data ? "onUpdates"
118
- : data.onSyncRequest ? "onSyncRequest"
119
- : "onPullRequest",
120
- tableName,
121
- channelName,
122
- data,
123
- syncedTable,
124
- });
125
- });
117
+ // syncedTables.get(channelName)?.then((syncedTable) => {
118
+ // onDebug?.({
119
+ // type: "sync",
120
+ // command:
121
+ // data.data ? "onUpdates"
122
+ // : data.onSyncRequest ? "onSyncRequest"
123
+ // : "onPullRequest",
124
+ // tableName,
125
+ // channelName,
126
+ // data,
127
+ // options: { n filter, select },
128
+ // });
129
+ // });
126
130
  if (data.data) {
127
131
  Promise.resolve(onUpdates(data))
128
132
  .then(() => {
@@ -156,8 +160,8 @@ const getSyncHandler = ({ socket, onDebug }) => {
156
160
  syncs.set(channelName, {
157
161
  tableName,
158
162
  command,
159
- filter,
160
- select,
163
+ param1,
164
+ param2,
161
165
  clientSyncHandles: [clientSyncHandlers],
162
166
  syncInfo: sync_info,
163
167
  onCall,
@@ -0,0 +1,14 @@
1
+ import { type AnyObject, type ValidatedColumnInfo } from "prostgles-types";
2
+ import type { DBHandlerClient, InitOptions } from "./prostgles";
3
+ import type { Sync, SyncOne } from "./SyncedTable/SyncedTable";
4
+ export declare const getSyncHandlerV2: ({ socket, onDebug }: Pick<InitOptions, "socket" | "onDebug">) => {
5
+ getTableSyncFunctions: ({ db, tableName, columns, }: {
6
+ db: Partial<DBHandlerClient>;
7
+ tableName: string;
8
+ columns: ValidatedColumnInfo[];
9
+ }) => Promise<{
10
+ addSync: Sync<AnyObject>;
11
+ addSyncOne: SyncOne<AnyObject>;
12
+ }>;
13
+ };
14
+ //# sourceMappingURL=getSyncHandlerV2.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getSyncHandlerV2.d.ts","sourceRoot":"","sources":["../lib/getSyncHandlerV2.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,SAAS,EAId,KAAK,mBAAmB,EACzB,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAEhE,OAAO,KAAK,EAAwB,IAAI,EAAE,OAAO,EAAE,MAAM,2BAA2B,CAAC;AAErF,eAAO,MAAM,gBAAgB,GAAI,qBAAqB,IAAI,CAAC,WAAW,EAAE,QAAQ,GAAG,SAAS,CAAC;yDA8CxF;QACD,EAAE,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC;QAC7B,SAAS,EAAE,MAAM,CAAC;QAClB,OAAO,EAAE,mBAAmB,EAAE,CAAC;KAChC;;;;CAiBF,CAAC"}