prostgles-server 4.2.9 → 4.2.12

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.
@@ -1,581 +0,0 @@
1
- import { strict as assert } from 'assert';
2
- import type { DBHandlerClient, Auth } from "./client/index";
3
- import { DBSchemaTable, SocketSQLStreamPacket, isDefined } from "prostgles-types";
4
- import { tryRun, tryRunP } from './isomorphic_queries';
5
- import { reject } from 'bluebird';
6
-
7
- export default async function client_only(db: DBHandlerClient, auth: Auth, log: (...args: any[]) => any, methods, tableSchema: DBSchemaTable[], token: string){
8
-
9
- await tryRunP("SQL Stream persistedConnection with streamLimit works for subsequent queries", async (resolve, reject) => {
10
- const query = "SELECT * FROM generate_series(1, 100)";
11
- let results: any[] = [];
12
- const streamLimit = 10;
13
- const res = await db.sql!(query, {}, { returnType: "stream", persistStreamConnection: true, streamLimit });
14
- const listener = async (packet: SocketSQLStreamPacket) => {
15
- try {
16
-
17
- if(packet.type === "error"){
18
- reject(packet.error);
19
- } else {
20
- results = results.concat(packet.rows);
21
- if(results.length === streamLimit){
22
- assert.equal(packet.type, "data");
23
- assert.equal(packet.ended, true);
24
- assert.equal(packet.rows.length, 10);
25
- startHandler.run(`SELECT '${query}' as query`).catch(reject);
26
- } else {
27
- assert.equal(packet.type, "data");
28
- assert.equal(packet.ended, true);
29
- assert.equal(packet.rows.length, 1);
30
- assert.equal(packet.rows[0][0], query);
31
- resolve("ok");
32
- }
33
- }
34
- } catch(err){
35
- reject(err);
36
- }
37
- };
38
- const startHandler = await res.start(listener);
39
- });
40
-
41
- await tryRunP("SQL Stream ensure the connection is never released (same pg_backend_pid is the same for subsequent) when using persistConnectionId", async (resolve, reject) => {
42
- const query = "SELECT pg_backend_pid()";
43
- const res = await db.sql!(query, {}, { returnType: "stream", persistStreamConnection: true });
44
- const pids: number[] = [];
45
- const listener = async (packet: SocketSQLStreamPacket) => {
46
- if(packet.type === "error"){
47
- reject(packet.error);
48
- } else {
49
- assert.equal(packet.type, "data");
50
- assert.equal(packet.ended, true);
51
- assert.equal(packet.rows.length, 1);
52
- const pid = packet.rows[0][0];
53
- pids.push(pid);
54
- if(pids.length === 1){
55
- startHandler.run(query).catch(reject);
56
- }
57
- if(pids.length === 2){
58
- assert.equal(pids[0], pids[1]);
59
- resolve("ok");
60
- }
61
- }
62
- };
63
- const startHandler = await res.start(listener);
64
- });
65
-
66
- await tryRunP("SQL Stream stop kills the query", async (resolve, reject) => {
67
- const query = "SELECT * FROM pg_sleep(5)";
68
- const res = await db.sql!(query, {}, { returnType: "stream" });
69
- const listener = async (packet: SocketSQLStreamPacket) => {
70
- if(packet.type === "error"){
71
- const queryState = await db.sql!("SELECT * FROM pg_stat_activity WHERE query = $1", [query], { returnType: "rows" });
72
- assert.equal(queryState.length, 1);
73
- assert.equal(queryState[0].state, "idle");
74
- assert.equal(packet.error.message, "canceling statement due to user request");
75
- resolve("ok");
76
- } else {
77
- assert.equal(packet.type, "data");
78
- assert.equal(packet.ended, true);
79
- assert.deepStrictEqual(packet.rows, [['']]);
80
- reject("SQL Stream stop kills the query");
81
- }
82
- };
83
- const startHandler = await res.start(listener);
84
- setTimeout(() => {
85
- startHandler.stop().catch(reject);
86
- }, 1000);
87
- });
88
-
89
- await tryRunP("SQL Stream limit works", async (resolve, reject) => {
90
- const res = await db.sql!("SELECT * FROM generate_series(1, 1e5)", {}, { returnType: "stream", streamLimit: 10 });
91
- const listener = async (packet: SocketSQLStreamPacket) => {
92
- if(packet.type === "error"){
93
- reject(packet.error);
94
- } else {
95
- assert.equal(packet.type, "data");
96
- assert.equal(packet.ended, true);
97
- assert.equal(packet.rows.length, 10);
98
- resolve("ok");
99
- }
100
- };
101
- await res.start(listener);
102
- });
103
-
104
- await tryRunP("SQL Stream stop with terminate kills the query", async (resolve, reject) => {
105
- const totalRows = 5e6;
106
- const query = `SELECT * FROM generate_series(1, ${totalRows})`;
107
- const res = await db.sql!(query, {}, { returnType: "stream" });
108
- const rowsReceived: any[] = [];
109
- const listener = async (packet: SocketSQLStreamPacket) => {
110
- if(packet.type === "error"){
111
- const queryState = await db.sql!("SELECT * FROM pg_stat_activity WHERE query = $1", [query], { returnType: "rows" });
112
- assert.equal(queryState.length, 0);
113
- resolve("ok");
114
- } else {
115
- try {
116
- rowsReceived.push(...packet.rows);
117
- console.log(rowsReceived.length)
118
- assert.equal(packet.ended, false);
119
- assert.equal(rowsReceived.length < totalRows, true);
120
- } catch(error){
121
- reject(error);
122
- }
123
- }
124
- };
125
- const startHandler = await res.start(listener);
126
- setTimeout(() => {
127
- startHandler.stop(true).catch(reject);
128
- }, 22);
129
- });
130
-
131
- await Promise.all([1e3, 1e2].map(async (numberOfRows) => {
132
- await tryRunP("SQL Stream", async (resolve) => {
133
- const res = await db.sql!(`SELECT v.* FROM generate_series(1, ${numberOfRows}) v`, {}, { returnType: "stream" });
134
- let rows: any[] = [];
135
- const listener = async (packet: SocketSQLStreamPacket) => {
136
- if(packet.type === "error"){
137
- reject(packet.error);
138
- } else {
139
- rows = rows.concat(packet.rows);
140
- if(packet.ended){
141
- assert.equal(rows.length, numberOfRows);
142
- resolve("ok");
143
- }
144
- }
145
- };
146
- await res.start(listener);
147
- });
148
- }));
149
- await tryRunP("SQL Stream parallel execution + parameters", async (resolve, reject) => {
150
- const getExpected = (val: string) => new Promise(async (resolve, reject) => {
151
- const res = await db.sql!("SELECT ${val} as val", { val }, { returnType: "stream" });
152
- const listener = async (packet: SocketSQLStreamPacket) => {
153
- try {
154
- assert.equal(packet.type, "data");
155
- assert.equal(packet.ended, true);
156
- assert.deepStrictEqual(packet.rows, [[val]]);
157
- resolve(1);
158
- } catch(err){
159
- reject(err);
160
- }
161
- };
162
- await res.start(listener);
163
- });
164
- let resolved = 0;
165
- const expected = ["a", "b", "c"];
166
- expected.forEach((val) => {
167
- getExpected(val).then(() => {
168
- resolved++;
169
- if(resolved === expected.length){
170
- resolve("ok");
171
- }
172
- }).catch(reject);
173
- })
174
- });
175
- await tryRunP("SQL Stream query error structure matches default sql run error", async (resolve, reject) => {
176
- const badQuery = "SELECT * FROM not_existing_table"
177
- const res = await db.sql!(badQuery, {}, { returnType: "stream" });
178
- const listener = async (packet: SocketSQLStreamPacket) => {
179
- try {
180
- const normalSqlError = await db.sql!(badQuery, {}).catch(err => err);
181
- assert.equal(packet.type, "error");
182
- assert.equal(packet.error.message, 'relation "not_existing_table" does not exist');
183
- assert.deepEqual(packet.error, normalSqlError);
184
- resolve("ok");
185
- } catch(err){
186
- reject(err);
187
- }
188
- };
189
- await res.start(listener);
190
- });
191
- await tryRunP("SQL Stream streamLimit", async (resolve, reject) => {
192
- const generate_series = "SELECT * FROM generate_series(1, 100)";
193
- const res = await db.sql!(generate_series, {}, { returnType: "stream", streamLimit: 10 });
194
- const listener = async (packet: SocketSQLStreamPacket) => {
195
- if(packet.type === "error"){
196
- reject(packet.error);
197
- } else {
198
- assert.equal(packet.type, "data");
199
- assert.equal(packet.ended, true);
200
- assert.equal(packet.rows.length, 10);
201
-
202
- const normalSql = await db.sql!(generate_series, {});
203
-
204
- /** fields the same as on normal sql request */
205
- assert.deepStrictEqual(packet.fields, normalSql.fields);
206
-
207
- /** result is rowMode=array */
208
- assert.equal(Array.isArray(packet.rows), true);
209
- assert.equal(Array.isArray(packet.rows[0]), true);
210
-
211
- assert.deepStrictEqual(packet.rows.flat(), Array.from({ length: 10 }, (_, i) => i + 1).flat());
212
- resolve("ok");
213
- }
214
- };
215
- await res.start(listener);
216
- });
217
-
218
- await tryRunP("SQL Stream table fields are the same as on default request", async (resolve, reject) => {
219
- await db.sql!("INSERT INTO planes (last_updated) VALUES (56789);", {});
220
- const res = await db.sql!("SELECT * FROM planes", {}, { returnType: "stream" });
221
- const listener = async (packet: SocketSQLStreamPacket) => {
222
- if(packet.type === "error"){
223
- reject(packet.error);
224
- } else {
225
- assert.equal(packet.type, "data");
226
- assert.equal(packet.ended, true);
227
- assert.equal(packet.rows.length, 1);
228
- const normalSql = await db.sql!("SELECT * FROM planes LIMIT 1", {});
229
- await db.sql!("DELETE FROM planes", {});
230
- assert.deepStrictEqual(packet.fields, normalSql.fields);
231
- assert.equal(packet.fields.length > 0, true);
232
- resolve("ok");
233
- }
234
- };
235
- await res.start(listener);
236
- });
237
- await tryRunP("SQL Stream works for multiple statements", async (resolve, reject) => {
238
- const res = await db.sql!("SELECT * FROM planes; SELECT 1 as a", {}, { returnType: "stream" });
239
- const listener = async (packet: SocketSQLStreamPacket) => {
240
- if(packet.type === "error"){
241
- reject(packet.error);
242
- } else {
243
- assert.equal(packet.type, "data");
244
- assert.equal(packet.ended, true);
245
- assert.equal(packet.rows.length, 1);
246
- const normalSql = await db.sql!("SELECT 1 as a", {});
247
- await db.sql!("DELETE FROM planes", {});
248
- assert.deepStrictEqual(packet.fields, normalSql.fields);
249
- assert.equal(packet.fields.length > 0, true);
250
- resolve("ok");
251
- }
252
- };
253
- await res.start(listener);
254
- });
255
-
256
-
257
- /**
258
- * tableSchema must contan an array of all tables and their columns that have getInfo and getColumns allowed
259
- */
260
- await tryRun("Check tableSchema", async () => {
261
- const dbTables = Object.keys(db).map(k => {
262
- const h = db[k];
263
- return !!(h.getColumns && h.getInfo)? k : undefined;
264
- }).filter(isDefined);
265
- const missingTbl = dbTables.find(t => !tableSchema.some(st => st.name === t));
266
- if(missingTbl) throw `${missingTbl} is missing from tableSchema: ${JSON.stringify(tableSchema)}`
267
- const missingscTbl = tableSchema.find(t => !dbTables.includes(t.name));
268
- if(missingscTbl) throw `${missingscTbl} is missing from db`;
269
-
270
- await Promise.all(tableSchema.map(async tbl => {
271
- const cols = await db[tbl.name]?.getColumns?.();
272
- const info = await db[tbl.name]?.getInfo?.();
273
- assert.deepStrictEqual(tbl.columns, cols);
274
- assert.deepStrictEqual(tbl.info, info);
275
- }))
276
- });
277
-
278
- const testRealtime = () => {
279
- return new Promise(async (resolve, reject) => {
280
- try {
281
-
282
- /* METHODS */
283
- const t222 = await methods.get();
284
- assert.equal(t222, 222, "methods.get() failed");
285
-
286
- /* RAWSQL */
287
- await tryRun("SQL Full result", async () => {
288
- if(!db.sql) throw "db.sql missing";
289
- const sqlStatement = await db.sql("SELECT $1", [1], { returnType: "statement" });
290
- assert.equal(sqlStatement, "SELECT 1", "db.sql statement query failed");
291
-
292
-
293
- await db.sql("SELECT 1 -- ${param}", {}, { hasParams: false });
294
-
295
- const arrayMode = await db.sql("SELECT 1 as a, 2 as a", undefined, { returnType: "arrayMode" });
296
- assert.equal(arrayMode.rows?.[0].join("."), "1.2", "db.sql statement arrayMode failed");
297
- assert.equal(arrayMode.fields?.map(f => f.name).join("."), "a.a", "db.sql statement arrayMode failed");
298
-
299
- const select1 = await db.sql("SELECT $1 as col1", [1], { returnType: "rows" });
300
- assert.deepStrictEqual(select1[0], { col1: 1 }, "db.sql justRows query failed");
301
-
302
- const fullResult = await db.sql("SELECT $1 as col1", [1]);
303
- // console.log(fullResult)
304
- assert.deepStrictEqual(fullResult.rows[0], { col1: 1 }, "db.sql query failed");
305
- assert.deepStrictEqual(fullResult.fields, [ {
306
- name: 'col1',
307
- tableID: 0,
308
- columnID: 0,
309
- dataTypeID: 23,
310
- dataTypeSize: 4,
311
- dataTypeModifier: -1,
312
- format: 'text',
313
- dataType: 'int4',
314
- udt_name: 'int4',
315
- tsDataType: "number"
316
- }] , "db.sql query failed");
317
- });
318
-
319
- await tryRunP("sql LISTEN NOTIFY events", async (resolve, reject) => {
320
- if(!db.sql) throw "db.sql missing";
321
-
322
- try {
323
-
324
- const sub = await db.sql("LISTEN chnl ", {}, { allowListen: true, returnType: "arrayMode" });
325
- if(!("addListener" in sub)) {
326
- reject("addListener missing");
327
- return
328
- }
329
-
330
- sub.addListener(notif => {
331
- const expected = "hello"
332
- if(notif === expected) resolve(true);
333
- else reject(`Notif value is not what we expect: ${JSON.stringify(notif)} is not ${JSON.stringify(expected)} (expected) `)
334
- });
335
- db.sql("NOTIFY chnl , 'hello'; ");
336
- } catch(e){
337
- reject(e);
338
- }
339
- });
340
-
341
- await tryRunP("sql NOTICE events", async (resolve, reject) => {
342
- if(!db.sql) throw "db.sql missing";
343
-
344
- const sub = await db.sql("", {}, { returnType: "noticeSubscription" });
345
-
346
- sub.addListener(notice => {
347
- const expected = "hello2"
348
- if(notice.message === expected) resolve(true);
349
- else reject(`Notice value is not what we expect: ${JSON.stringify(notice)} is not ${JSON.stringify(expected)} (expected) `)
350
- });
351
- db.sql(`
352
- DO $$
353
- BEGIN
354
-
355
- RAISE NOTICE 'hello2';
356
-
357
- END $$;
358
- `);
359
- }, { log });
360
-
361
-
362
- /* REPLICATION */
363
- log("Started testRealtime")
364
- const start = Date.now();
365
-
366
- await db.planes.delete!();
367
- let inserts = new Array(100).fill(null).map((d, i) => ({ id: i, flight_number: `FN${i}`, x: Math.random(), y: i }));
368
- await db.planes.insert!(inserts);
369
-
370
- const CLOCK_DRIFT = 2000;
371
-
372
- if((await db.planes.count!()) !== 100) throw "Not 100 planes";
373
-
374
- /**
375
- * Two listeners are added at the same time to dbo.planes (which has 100 records):
376
- * subscribe({ x: 10 }
377
- * sync({}
378
- *
379
- * Then sync starts updating x to 10 for each record
380
- * subscribe waits for 100 records of x=10 and then updates everything to x=20
381
- * sync waits for 100 records of x=20 and finishes the test
382
- */
383
-
384
- /* After all sync records are updated to x10 here we'll update them to x20 */
385
- const sP = await db.planes.subscribe!({ x: 10 }, { }, async planes => {
386
-
387
- const p10 = planes.filter(p => p.x == 10);
388
- log(Date.now() + ": sub stats: x10 -> " + p10.length + " x20 ->" + planes.filter(p => p.x == 20).length);
389
-
390
- if(p10.length === 100){
391
-
392
- /** 2 second delay to account for client-server clock drift */
393
- setTimeout(async () => {
394
-
395
- // db.planes.findOne({}, { select: { last_updated: "$max"}}).then(log);
396
-
397
- await sP.unsubscribe();
398
- log(Date.now() + ": sub: db.planes.update({}, { x: 20, last_updated });");
399
- const dLastUpdated = Math.max(...p10.map(v => +v.last_updated))
400
- const last_updated = Date.now();
401
- if(dLastUpdated >= last_updated) throw "dLastUpdated >= last_updated should not happen"
402
- await db.planes.update!({}, { x: 20, last_updated });
403
- log(Date.now() + ": sub: Updated to x20" , await db.planes.count!({ x: 20 }))
404
-
405
- // db.planes.findOne({}, { select: { last_updated: "$max"}}).then(log)
406
- }, CLOCK_DRIFT)
407
- }
408
- });
409
-
410
- let updt = 0;
411
- const sync = await db.planes.sync!({}, { handlesOnData: true, patchText: true, }, (planes, deltas) => {
412
- const x20 = planes.filter(p => p.x == 20).length;
413
- const x10 = planes.filter(p => p.x == 10);
414
- log(Date.now() + `: sync stats: x10 -> ${x10.length} x20 -> ${x20}`);
415
-
416
- let update = false;
417
- planes.map(p => {
418
- // if(p.y === 1) window.up = p;
419
- if(typeof p.x !== "number") log(typeof p.x)
420
- if(+p.x < 10){
421
- updt++;
422
- update = true;
423
- p.$update!({ x: 10 });
424
- log(Date.now() + `: sync: p.$update({ x: 10 }); (id: ${p.id})`);
425
- }
426
- });
427
- // if(update) log("$update({ x: 10 })", updt)
428
-
429
- if(x20 === 100){
430
- // log(22)
431
- // console.timeEnd("test")
432
- log(Date.now() + ": sync end: Finished replication test. Inserting 100 rows then updating two times took: " + (Date.now() - start - CLOCK_DRIFT) + "ms")
433
- resolve(true)
434
- }
435
- });
436
-
437
-
438
- const msLimit = 20000;
439
- setTimeout(async () => {
440
- const dbCounts = {
441
- x10: await db.planes.count!({ x: 10 }),
442
- x20: await db.planes.count!({ x: 20 }),
443
- latest: await db.planes.findOne!({}, { orderBy: { last_updated: -1 } }),
444
- }
445
- const syncCounts = {
446
- x10: sync?.getItems().filter(d => d.x == 10).length,
447
- x20: sync?.getItems().filter(d => d.x == 20).length,
448
- latest: sync?.getItems()?.sort((a, b) => +b.last_updated - +a.last_updated )[0],
449
- }
450
- const msg = "Replication test failed due to taking longer than " + msLimit + "ms \n " + JSON.stringify({ dbCounts, syncCounts }, null, 2);
451
- log(msg)
452
- reject(msg)
453
- }, msLimit);
454
-
455
-
456
- } catch(err){
457
- log(JSON.stringify(err));
458
- await tout(1000);
459
- throw err;
460
- }
461
- });
462
-
463
- }
464
-
465
-
466
-
467
- /* TODO: SECURITY */
468
- log("auth.user:", auth.user)
469
- if(!auth.user){
470
- log("Checking public data");
471
- // Public data
472
- await tryRun("Security rules example", async () => {
473
- const vQ = await db.items4.find!({}, { select: { added: 0 }});
474
- assert.deepStrictEqual(vQ, [
475
- { id: 1, public: 'public data' },
476
- { id: 2, public: 'public data' }
477
- ]);
478
-
479
- const cols = await db.insert_rules.getColumns!();
480
- assert.equal(cols.filter(({ insert, update: u, select: s, delete: d }) => insert && !u && s && !d).length, 2, "Validated getColumns failed")
481
-
482
- /* Validated insert */
483
- const expectB = await db.insert_rules.insert!({ name: "a" }, { returning: "*" });
484
- assert.deepStrictEqual(expectB, { name: "b" }, "Validated insert failed");
485
-
486
- /* forced UUID insert */
487
- const row: any = await db.uuid_text.insert!({}, {returning: "*"});
488
- assert.equal(row.id, 'c81089e1-c4c1-45d7-a73d-e2d613cb7c3e');
489
-
490
-
491
- try {
492
- await db.insert_rules.insert!({ name: "notfail" }, { returning: "*" });
493
- await db.insert_rules.insert!({ name: "fail" }, { returning: "*" });
494
- await db.insert_rules.insert!({ name: "fail-check" }, { returning: "*" });
495
- throw "post insert checks should have failed";
496
- } catch(err){
497
-
498
- }
499
- assert.equal(0, +(await db.insert_rules.count!({ name: "fail" })), "postValidation failed");
500
- assert.equal(0, +(await db.insert_rules.count!({ name: "fail-check" })), "checkFilter failed");
501
- assert.equal(1, +(await db.insert_rules.count!({ name: "notfail" })), "postValidation failed");
502
- });
503
-
504
- // await tryRun("Duplicate subscription", async () => {
505
-
506
- // return new Promise(async (resolve, reject) => {
507
- // let data1 = [], data2 = [], cntr = 0;
508
- // function check(){
509
- // cntr++;
510
- // if(cntr === 2){
511
- // assert.equal(data1.length, data2.length);
512
- // console.error(data1, data2)
513
- // reject( data1);
514
- // resolve(data1)
515
- // }
516
- // }
517
-
518
- // const sub1 = await db.planes.subscribe({}, {}, data => {
519
- // data1 = data;
520
- // check()
521
- // });
522
- // const sub2 = await db.planes.subscribe({}, {}, data => {
523
- // data2 = data;
524
- // check()
525
- // });
526
- // })
527
- // })
528
-
529
-
530
-
531
- await testRealtime();
532
-
533
- // auth.login({ username: "john", password: "secret" });
534
-
535
- // await tout();
536
-
537
- } else {
538
- log("Checking User data");
539
- // User data
540
- await tryRun("Security rules example", async () => {
541
- const vQ = await db.items4.find!();
542
- assert.deepStrictEqual(vQ, [
543
- { id: 1, public: 'public data' },
544
- { id: 2, public: 'public data' }
545
- ]);
546
-
547
- await db.items4.find!({}, { select: { id: 1 }, orderBy: { added: 1 } });
548
-
549
- const dynamicCols = await db.uuid_text.getColumns!(undefined, {
550
- rule: "update",
551
- filter: {
552
- id: 'c81089e1-c4c1-45d7-a73d-e2d613cb7c3e'
553
- },
554
- data: {
555
- id: "dwadwa"
556
- }
557
- });
558
- assert.equal(dynamicCols.length, 1);
559
- assert.equal(dynamicCols[0].name, "id");
560
- const defaultCols = await db.uuid_text.getColumns!(undefined, {
561
- rule: "update",
562
- filter: {
563
- id: 'not matching'
564
- },
565
- data: {
566
- id: "dwadwa"
567
- }
568
- });
569
- throw defaultCols.map(c => c.name);
570
- }, log);
571
- }
572
-
573
- }
574
-
575
- const tout = (t = 3000) => {
576
- return new Promise(async (resolve, reject) => {
577
- setTimeout(() => {
578
- resolve(true)
579
- },t)
580
- });
581
- }
@@ -1,79 +0,0 @@
1
- import { strict as assert } from 'assert';
2
- import type { DBHandlerClient, Auth } from "./client/index";
3
- import { DBSchemaTable } from "prostgles-types";
4
- import { tryRun } from './isomorphic_queries';
5
-
6
- export default async function client_rest_api(db: DBHandlerClient, auth: Auth, log: (...args: any[]) => any, methods, tableSchema: DBSchemaTable[], token: string){
7
-
8
- const post = async ({ path, noAuth }: { path: string; noAuth?: boolean}, ...params: any[]) => {
9
- const headers = new Headers({
10
- 'Authorization': `Bearer ${Buffer.from(noAuth? "noAuth" : token, "utf-8").toString("base64")}`,
11
- 'Accept': 'application/json',
12
- 'Content-Type': 'application/json'
13
- });
14
- const res = await fetch(`http://127.0.0.1:3001/api/${path}`, {
15
- method: "POST",
16
- headers,
17
- body: !params?.length? undefined : JSON.stringify(params)
18
- });
19
- const resBodyJson = await res.text()
20
- .then(text => {
21
- try {
22
- return JSON.parse(text);
23
- } catch {
24
- return text;
25
- }
26
- });
27
-
28
- if(res.status !== 200){
29
- return Promise.reject(resBodyJson);
30
- }
31
- return resBodyJson;
32
- }
33
- const rest = async ({ tableName, command, noAuth }: { tableName: string; command: string; noAuth?: boolean; }, ...params: any[]) => post({ path: `db/${tableName}/${command}`, noAuth }, ...(params ?? []))
34
- const dbRest = (tableName: string, command: string, ...params: any[]) => rest({ tableName, command }, ...(params ?? []))
35
- const dbRestNoAuth = (tableName: string, command: string, ...params: any[]) => rest({ tableName, command, noAuth: true }, ...(params ?? []));
36
- const sqlRest = (query: string, ...params: any[]) => post({ path: `db/sql` }, query, ...(params ?? []))
37
- const sqlMethods = (methodName: string, ...params: any[]) => post({ path: `methods/${methodName}` }, ...(params ?? []))
38
-
39
- await tryRun("Rest api test", async () => {
40
- const dataFilter = { id: 123123123, last_updated: Date.now() };
41
- const dataFilter1 = { id: 123123124, last_updated: Date.now() };
42
- await db.planes.insert(dataFilter);
43
- const item = await db.planes.findOne(dataFilter);
44
- const itemR = await dbRest("planes", "findOne", dataFilter);
45
- const itemRNA = await dbRestNoAuth("planes", "findOne", dataFilter);
46
- assert.deepStrictEqual(item, itemR);
47
- const { last_updated, ...allowedData } = item;
48
- assert.deepStrictEqual(allowedData, itemRNA);
49
-
50
- await dbRest("planes", "insert", dataFilter1);
51
- const filter = { "id.>=": dataFilter.id }
52
- const count = await db.planes.count(filter)
53
- const restCount = await dbRest("planes", "count", filter);
54
- assert.equal(count, 2);
55
- assert.equal(restCount, 2);
56
-
57
- const sqlRes = await sqlRest("select 1 as a", {}, { returnType: "rows" });
58
- assert.deepStrictEqual(sqlRes, [{ a: 1 }]);
59
-
60
- const restTableSchema = await post({ path: "schema" });
61
- assert.deepStrictEqual(tableSchema, restTableSchema.tableSchema);
62
- await Promise.all(tableSchema.map(async tbl => {
63
- const cols = await db[tbl.name]?.getColumns?.();
64
- const info = await db[tbl.name]?.getInfo?.();
65
- if(db[tbl.name]?.getColumns){
66
- const restCols = await dbRest(tbl.name, "getColumns", {});
67
- assert.deepStrictEqual(tbl.columns, cols);
68
- assert.deepStrictEqual(tbl.columns, restCols);
69
- assert.deepStrictEqual(tbl.info, info);
70
- }
71
- }));
72
-
73
- const two22 = await sqlMethods("get", {});
74
- assert.equal(two22, 222);
75
-
76
- });
77
-
78
-
79
- }