soul-cli 0.8.1 → 0.9.3

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 (71) hide show
  1. package/.all-contributorsrc +9 -0
  2. package/.bruno/auth/folder.bru +8 -0
  3. package/.bruno/auth/obtain-access-token.bru +25 -0
  4. package/.bruno/bruno.json +6 -0
  5. package/.bruno/environments/local.bru +3 -0
  6. package/.bruno/rows/folder.bru +8 -0
  7. package/.bruno/rows/list-rows-with-ordering.bru +25 -0
  8. package/.bruno/tables/folder.bru +8 -0
  9. package/.bruno/tables/list-tables.bru +16 -0
  10. package/.env.sample +11 -2
  11. package/.github/dependabot.yml +9 -0
  12. package/.github/workflows/ci.yml +33 -0
  13. package/.github/workflows/npm-publish.yml +19 -6
  14. package/.husky/pre-commit +0 -3
  15. package/README.md +46 -7
  16. package/ROADMAP.md +154 -0
  17. package/assets/images/soul-RA-app.png +0 -0
  18. package/assets/images/soul-standalone.png +0 -0
  19. package/docs/extensions-examples.md +96 -16
  20. package/docs/self-hosting.md +54 -0
  21. package/docs/ws-examples.md +4 -0
  22. package/eslint.config.js +29 -0
  23. package/package.json +40 -20
  24. package/scripts/dev.sh +64 -0
  25. package/src/cli.test.js +128 -0
  26. package/src/config/index.js +10 -2
  27. package/src/config/index.test.js +120 -0
  28. package/src/controllers/auth/common.js +1 -16
  29. package/src/controllers/auth/common.test.js +23 -0
  30. package/src/controllers/auth/tables.js +1 -1
  31. package/src/controllers/auth/token.js +30 -7
  32. package/src/controllers/auth/user.js +20 -20
  33. package/src/controllers/auth/user.test.js +232 -0
  34. package/src/controllers/auth.test.js +445 -0
  35. package/src/controllers/rows.js +183 -120
  36. package/src/controllers/rows.test.js +119 -2
  37. package/src/controllers/tables.js +63 -17
  38. package/src/controllers/tables.test.js +185 -0
  39. package/src/db/index.test.js +21 -0
  40. package/src/extensions.js +105 -36
  41. package/src/extensions.test.js +340 -0
  42. package/src/index.js +29 -20
  43. package/src/index.test.js +118 -0
  44. package/src/middlewares/api.js +1 -1
  45. package/src/middlewares/api.test.js +29 -0
  46. package/src/middlewares/auth.js +11 -48
  47. package/src/middlewares/auth.test.js +105 -0
  48. package/src/middlewares/validation.test.js +60 -0
  49. package/src/schemas/index.js +3 -1
  50. package/src/schemas/rows.js +16 -6
  51. package/src/schemas/tables.js +28 -4
  52. package/src/server.js +83 -1
  53. package/src/services/authService.js +33 -3
  54. package/src/services/authService.test.js +115 -0
  55. package/src/services/rowService.js +39 -14
  56. package/src/services/rowService.test.js +153 -0
  57. package/src/services/tableService.js +15 -17
  58. package/src/services/tableService.test.js +190 -0
  59. package/src/swagger/swagger.json +4 -7
  60. package/src/tests/globalSetup.js +8 -1
  61. package/src/tests/index.js +23 -0
  62. package/src/utils/index.js +25 -2
  63. package/src/utils/index.test.js +135 -0
  64. package/src/utils/logger.js +15 -0
  65. package/src/utils/sql.js +112 -0
  66. package/src/utils/sql.test.js +115 -0
  67. package/src/websocket.js +46 -8
  68. package/src/websocket.test.js +121 -0
  69. package/.eslintignore +0 -2
  70. package/.eslintrc.js +0 -24
  71. package/src/middlewares/logger.js +0 -13
@@ -0,0 +1,135 @@
1
+ const {
2
+ hashPassword,
3
+ hashPasswordSync,
4
+ comparePasswords,
5
+ checkPasswordStrength,
6
+ generateToken,
7
+ decodeToken,
8
+ toBoolean,
9
+ removeFields,
10
+ } = require('./index');
11
+
12
+ describe('utils', () => {
13
+ describe('hashPassword / comparePasswords', () => {
14
+ it('produces a hash that verifies against the original password', async () => {
15
+ const { hashedPassword, salt } = await hashPassword('Str0ng$Pw!', 10);
16
+
17
+ expect(typeof hashedPassword).toBe('string');
18
+ expect(typeof salt).toBe('string');
19
+ expect(await comparePasswords('Str0ng$Pw!', hashedPassword)).toBe(true);
20
+ expect(await comparePasswords('wrong-password', hashedPassword)).toBe(
21
+ false,
22
+ );
23
+ });
24
+ });
25
+
26
+ describe('hashPasswordSync', () => {
27
+ it('produces a hash that verifies synchronously-generated and async-compared', async () => {
28
+ const { hashedPassword } = hashPasswordSync('Str0ng$Pw!', 10);
29
+
30
+ expect(await comparePasswords('Str0ng$Pw!', hashedPassword)).toBe(true);
31
+ });
32
+ });
33
+
34
+ describe('checkPasswordStrength', () => {
35
+ it('flags a weak password', () => {
36
+ expect(['Too weak', 'Weak']).toContain(checkPasswordStrength('12345678'));
37
+ });
38
+
39
+ it('accepts a strong password', () => {
40
+ expect(checkPasswordStrength('HeK34#C44DMJ')).toBe('Strong');
41
+ });
42
+ });
43
+
44
+ describe('generateToken / decodeToken', () => {
45
+ it('round-trips a payload through a signed token', async () => {
46
+ const token = await generateToken({ userId: 1 }, 'test-secret', '1H');
47
+ const decoded = await decodeToken(token, 'test-secret');
48
+
49
+ expect(decoded.userId).toBe(1);
50
+ });
51
+
52
+ it('throws for a token signed with a different secret', async () => {
53
+ const token = await generateToken({ userId: 1 }, 'secret-a', '1H');
54
+
55
+ await expect(decodeToken(token, 'secret-b')).rejects.toThrow(
56
+ 'Invalid token',
57
+ );
58
+ });
59
+
60
+ it('throws for a malformed token', async () => {
61
+ await expect(decodeToken('not-a-token', 'test-secret')).rejects.toThrow(
62
+ 'Invalid token',
63
+ );
64
+ });
65
+
66
+ it('generates distinct tokens for identical payloads (no jti collision)', async () => {
67
+ // jwt.sign is otherwise deterministic for identical
68
+ // header+payload+secret -- two logins for the same user within the
69
+ // same second (identical iat/exp too) would produce byte-identical
70
+ // tokens without a unique jti, letting revocation of one silently
71
+ // revoke an unrelated concurrent session for that user.
72
+ const payload = { userId: 1, username: 'admin', isSuperuser: 'false' };
73
+ const [tokenA, tokenB] = await Promise.all([
74
+ generateToken(payload, 'test-secret', '1H'),
75
+ generateToken(payload, 'test-secret', '1H'),
76
+ ]);
77
+
78
+ expect(tokenA).not.toBe(tokenB);
79
+
80
+ const [decodedA, decodedB] = await Promise.all([
81
+ decodeToken(tokenA, 'test-secret'),
82
+ decodeToken(tokenB, 'test-secret'),
83
+ ]);
84
+ expect(decodedA.jti).toBeDefined();
85
+ expect(decodedA.jti).not.toBe(decodedB.jti);
86
+ });
87
+
88
+ it('attaches the original jwt error as the cause', async () => {
89
+ try {
90
+ await decodeToken('not-a-token', 'test-secret');
91
+ throw new Error('expected decodeToken to throw');
92
+ } catch (error) {
93
+ expect(error.cause).toBeDefined();
94
+ }
95
+ });
96
+ });
97
+
98
+ describe('toBoolean', () => {
99
+ it.each([
100
+ [true, true],
101
+ [false, false],
102
+ ['true', true],
103
+ ['false', false],
104
+ ['TRUE', true],
105
+ [1, true],
106
+ [0, false],
107
+ ])('converts %p to %p', (input, expected) => {
108
+ expect(toBoolean(input)).toBe(expected);
109
+ });
110
+
111
+ it('throws for a value that cannot be converted', () => {
112
+ expect(() => toBoolean('not-a-boolean')).toThrow(
113
+ 'Invalid value. Cannot convert to boolean.',
114
+ );
115
+ expect(() => toBoolean(2)).toThrow();
116
+ expect(() => toBoolean(null)).toThrow();
117
+ });
118
+ });
119
+
120
+ describe('removeFields', () => {
121
+ it('deletes the given fields from every row, mutating in place', async () => {
122
+ const rows = [
123
+ { id: 1, secret: 'a', keep: 'x' },
124
+ { id: 2, secret: 'b', keep: 'y' },
125
+ ];
126
+
127
+ await removeFields(rows, ['secret']);
128
+
129
+ expect(rows).toEqual([
130
+ { id: 1, keep: 'x' },
131
+ { id: 2, keep: 'y' },
132
+ ]);
133
+ });
134
+ });
135
+ });
@@ -0,0 +1,15 @@
1
+ const winston = require('winston');
2
+
3
+ const config = require('../config');
4
+
5
+ const logger = winston.createLogger({
6
+ level: config.isTest ? 'error' : config.isProduction ? 'info' : 'debug',
7
+ format: winston.format.combine(
8
+ winston.format.timestamp(),
9
+ winston.format.errors({ stack: true }),
10
+ winston.format.json(),
11
+ ),
12
+ transports: [new winston.transports.Console()],
13
+ });
14
+
15
+ module.exports = logger;
@@ -0,0 +1,112 @@
1
+ // SQLite cannot bind identifiers (table/column names) as `?` parameters in
2
+ // most DML/DDL positions -- those must be validated against the live schema
3
+ // (allowlisted) before being spliced into a query string. Values must always
4
+ // go through `?` bindings, never interpolation. `quoteIdentifier` is not
5
+ // itself an injection defense, just correct SQLite identifier quoting --
6
+ // only call it on names that have already been validated below.
7
+
8
+ const operators = {
9
+ eq: '=',
10
+ lt: '<',
11
+ gt: '>',
12
+ lte: '<=',
13
+ gte: '>=',
14
+ neq: '!=',
15
+ null: 'IS NULL',
16
+ notnull: 'IS NOT NULL',
17
+ };
18
+
19
+ const invalidRequestError = (message, status = 400) => {
20
+ const error = new Error(message);
21
+ error.status = status;
22
+ return error;
23
+ };
24
+
25
+ const quoteIdentifier = (identifier) =>
26
+ `"${String(identifier).replace(/"/g, '""')}"`;
27
+
28
+ // Escapes a value as a SQL literal for the rare DDL positions (e.g. a column
29
+ // DEFAULT) where `?` binding isn't available. Prefer `?` binding everywhere
30
+ // else.
31
+ const quoteLiteral = (value) => {
32
+ if (value === null || value === undefined) {
33
+ return 'NULL';
34
+ }
35
+ if (typeof value === 'number' && Number.isFinite(value)) {
36
+ return String(value);
37
+ }
38
+ if (typeof value === 'boolean') {
39
+ return value ? '1' : '0';
40
+ }
41
+ return `'${String(value).replace(/'/g, "''")}'`;
42
+ };
43
+
44
+ const assertValidTableName = (db, tableName) => {
45
+ const row = db
46
+ .prepare(
47
+ `SELECT name FROM sqlite_master WHERE type IN ('table', 'view') AND name = ?`,
48
+ )
49
+ .get(tableName);
50
+
51
+ if (!row) {
52
+ throw invalidRequestError(`Table '${tableName}' does not exist`, 404);
53
+ }
54
+
55
+ return tableName;
56
+ };
57
+
58
+ const getValidatedTableName = (db, tableName) => {
59
+ const row = db
60
+ .prepare(
61
+ `SELECT name FROM sqlite_master WHERE type IN ('table', 'view') AND name = ?`,
62
+ )
63
+ .get(tableName);
64
+
65
+ if (!row) {
66
+ throw invalidRequestError(`Table '${tableName}' does not exist`, 404);
67
+ }
68
+
69
+ return row.name;
70
+ };
71
+
72
+ // Uses the pragma_table_info(?) table-valued-function form (SQLite >=3.16)
73
+ // instead of `PRAGMA table_info(...)`, which doesn't support bound params --
74
+ // this form is a plain SELECT with a function-call argument, so it does.
75
+ const getTableColumns = (db, tableName) => {
76
+ return db.prepare('SELECT * FROM pragma_table_info(?)').all(tableName);
77
+ };
78
+
79
+ const assertValidColumnName = (db, tableName, columnName) => {
80
+ assertValidTableName(db, tableName);
81
+
82
+ const columns = getTableColumns(db, tableName);
83
+ const found = columns.some((column) => column.name === columnName);
84
+
85
+ if (!found) {
86
+ throw invalidRequestError(
87
+ `Column '${columnName}' does not exist on table '${tableName}'`,
88
+ );
89
+ }
90
+
91
+ return columnName;
92
+ };
93
+
94
+ const assertValidOperator = (operator) => {
95
+ if (!Object.prototype.hasOwnProperty.call(operators, operator)) {
96
+ throw invalidRequestError(`Invalid field operator '${operator}'`);
97
+ }
98
+
99
+ return operators[operator];
100
+ };
101
+
102
+ module.exports = {
103
+ operators,
104
+ invalidRequestError,
105
+ quoteIdentifier,
106
+ quoteLiteral,
107
+ assertValidTableName,
108
+ getValidatedTableName,
109
+ getTableColumns,
110
+ assertValidColumnName,
111
+ assertValidOperator,
112
+ };
@@ -0,0 +1,115 @@
1
+ const Database = require('better-sqlite3');
2
+
3
+ const {
4
+ assertValidTableName,
5
+ assertValidColumnName,
6
+ assertValidOperator,
7
+ quoteIdentifier,
8
+ quoteLiteral,
9
+ operators,
10
+ } = require('./sql');
11
+
12
+ describe('sql utils', () => {
13
+ let db;
14
+
15
+ beforeEach(() => {
16
+ db = new Database(':memory:');
17
+ db.exec('CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT)');
18
+ });
19
+
20
+ afterEach(() => {
21
+ db.close();
22
+ });
23
+
24
+ describe('assertValidTableName', () => {
25
+ it('returns the table name when it exists', () => {
26
+ expect(assertValidTableName(db, 'items')).toBe('items');
27
+ });
28
+
29
+ it('throws a 404 error when the table does not exist', () => {
30
+ expect(() => assertValidTableName(db, 'nope')).toThrow(/does not exist/);
31
+ try {
32
+ assertValidTableName(db, 'nope');
33
+ } catch (error) {
34
+ expect(error.status).toBe(404);
35
+ }
36
+ });
37
+
38
+ it('throws for an injection payload disguised as a table name', () => {
39
+ expect(() =>
40
+ assertValidTableName(db, 'items; DROP TABLE items; --'),
41
+ ).toThrow(/does not exist/);
42
+
43
+ // table should be untouched
44
+ expect(assertValidTableName(db, 'items')).toBe('items');
45
+ });
46
+ });
47
+
48
+ describe('assertValidColumnName', () => {
49
+ it('returns the column name when it exists', () => {
50
+ expect(assertValidColumnName(db, 'items', 'name')).toBe('name');
51
+ });
52
+
53
+ it('throws a 400 error when the column does not exist', () => {
54
+ expect(() => assertValidColumnName(db, 'items', 'bogus')).toThrow(
55
+ /does not exist/,
56
+ );
57
+ try {
58
+ assertValidColumnName(db, 'items', 'bogus');
59
+ } catch (error) {
60
+ expect(error.status).toBe(400);
61
+ }
62
+ });
63
+
64
+ it('throws when the table itself does not exist', () => {
65
+ expect(() => assertValidColumnName(db, 'nope', 'name')).toThrow(
66
+ /does not exist/,
67
+ );
68
+ });
69
+ });
70
+
71
+ describe('assertValidOperator', () => {
72
+ it('returns the SQL operator for a known key', () => {
73
+ expect(assertValidOperator('eq')).toBe(operators.eq);
74
+ expect(assertValidOperator('gte')).toBe(operators.gte);
75
+ });
76
+
77
+ it('throws for an unknown operator', () => {
78
+ expect(() => assertValidOperator('DROP TABLE')).toThrow(
79
+ /Invalid field operator/,
80
+ );
81
+ });
82
+ });
83
+
84
+ describe('quoteIdentifier', () => {
85
+ it('wraps an identifier in double quotes', () => {
86
+ expect(quoteIdentifier('name')).toBe('"name"');
87
+ });
88
+
89
+ it('escapes embedded double quotes', () => {
90
+ expect(quoteIdentifier('na"me')).toBe('"na""me"');
91
+ });
92
+ });
93
+
94
+ describe('quoteLiteral', () => {
95
+ it('quotes and escapes string values', () => {
96
+ expect(quoteLiteral("x'); DROP TABLE items; --")).toBe(
97
+ "'x''); DROP TABLE items; --'",
98
+ );
99
+ });
100
+
101
+ it('passes numbers through unquoted', () => {
102
+ expect(quoteLiteral(42)).toBe('42');
103
+ });
104
+
105
+ it('maps booleans to 0/1', () => {
106
+ expect(quoteLiteral(true)).toBe('1');
107
+ expect(quoteLiteral(false)).toBe('0');
108
+ });
109
+
110
+ it('maps null/undefined to NULL', () => {
111
+ expect(quoteLiteral(null)).toBe('NULL');
112
+ expect(quoteLiteral(undefined)).toBe('NULL');
113
+ });
114
+ });
115
+ });
package/src/websocket.js CHANGED
@@ -1,13 +1,18 @@
1
1
  const { WebSocketServer } = require('ws');
2
+ const cookie = require('cookie');
2
3
 
3
4
  const db = require('./db/index');
5
+ const config = require('./config/index');
6
+ const { decodeToken } = require('./utils/index');
7
+ const logger = require('./utils/logger');
8
+ const { authService } = require('./services');
4
9
 
5
10
  const wss = new WebSocketServer({ noServer: true });
6
11
 
7
12
  const websocketSubscribers = new Map();
8
13
 
9
- wss.on('connection', function (ws, request) {
10
- const [_path, params] = request?.url?.split('?');
14
+ wss.on('connection', async function (ws, request) {
15
+ const [_path, params] = (request.url || '').split('?');
11
16
 
12
17
  if (!_path.startsWith('/ws')) {
13
18
  ws.close();
@@ -17,15 +22,15 @@ wss.on('connection', function (ws, request) {
17
22
  const tableName = _path.replace('/ws/tables/', '').replace('/', '');
18
23
 
19
24
  // if table does not exists close the connection
20
- const query = `SELECT name FROM sqlite_master WHERE type='table' AND name='${tableName}'`;
25
+ const query = `SELECT name FROM sqlite_master WHERE type='table' AND name = ?`;
21
26
  try {
22
- const table = db.prepare(query).get();
27
+ const table = db.prepare(query).get(tableName);
23
28
 
24
29
  if (!table) {
25
30
  ws.send(
26
31
  JSON.stringify({
27
32
  message: `Table ${tableName} does not exist`,
28
- })
33
+ }),
29
34
  );
30
35
 
31
36
  ws.close();
@@ -35,12 +40,45 @@ wss.on('connection', function (ws, request) {
35
40
  ws.send(
36
41
  JSON.stringify({
37
42
  message: error.message,
38
- })
43
+ }),
39
44
  );
40
45
  ws.close();
41
46
  return;
42
47
  }
43
48
 
49
+ // realtime subscriptions carry the same read access requirements as the
50
+ // REST API -- unauthenticated/unauthorized clients must not be able to
51
+ // subscribe to row changes on a table they can't read via the REST API.
52
+ if (config.auth) {
53
+ const cookies = cookie.parse(request.headers.cookie || '');
54
+ const accessToken = cookies.accessToken;
55
+
56
+ if (!accessToken) {
57
+ ws.send(JSON.stringify({ message: 'Missing access token' }));
58
+ ws.close();
59
+ return;
60
+ }
61
+
62
+ let payload;
63
+ try {
64
+ payload = await decodeToken(accessToken, config.tokenSecret);
65
+ } catch {
66
+ ws.send(JSON.stringify({ message: 'Invalid access token' }));
67
+ ws.close();
68
+ return;
69
+ }
70
+
71
+ if (!authService.hasTablePermission({ payload, tableName, verb: 'GET' })) {
72
+ ws.send(
73
+ JSON.stringify({
74
+ message: `Not authorized to subscribe to table "${tableName}"`,
75
+ }),
76
+ );
77
+ ws.close();
78
+ return;
79
+ }
80
+ }
81
+
44
82
  if (!websocketSubscribers.has(tableName)) {
45
83
  websocketSubscribers.set(tableName, new Set());
46
84
  }
@@ -50,13 +88,13 @@ wss.on('connection', function (ws, request) {
50
88
  params: new URLSearchParams(params),
51
89
  };
52
90
 
53
- console.log(`New subscriber for table ${tableName}`);
91
+ logger.info(`New subscriber for table ${tableName}`);
54
92
  websocketSubscribers.get(tableName).add(subscriber);
55
93
 
56
94
  ws.send(JSON.stringify({ message: `Subscribed to table "${tableName}"` }));
57
95
 
58
96
  ws.on('message', function (message) {
59
- console.log('received: %s', message);
97
+ logger.debug(`received: ${message}`);
60
98
  });
61
99
 
62
100
  ws.on('close', function () {
@@ -0,0 +1,121 @@
1
+ const http = require('http');
2
+ const WebSocket = require('ws');
3
+ const supertest = require('supertest');
4
+
5
+ const app = require('./index');
6
+ const { wss } = require('./websocket');
7
+ const { generateToken } = require('./utils');
8
+ const config = require('./config');
9
+
10
+ describe('websocket', () => {
11
+ let server;
12
+ let port;
13
+
14
+ const wsUrl = (path) => `ws://localhost:${port}${path}`;
15
+
16
+ beforeAll((done) => {
17
+ server = http.createServer(app);
18
+ server.on('upgrade', (request, socket, head) => {
19
+ wss.handleUpgrade(request, socket, head, (ws) => {
20
+ wss.emit('connection', ws, request);
21
+ });
22
+ });
23
+ server.listen(0, () => {
24
+ port = server.address().port;
25
+ done();
26
+ });
27
+ });
28
+
29
+ afterAll((done) => {
30
+ wss.close();
31
+ server.close(done);
32
+ });
33
+
34
+ it('closes the connection with a message when the table does not exist', (done) => {
35
+ const ws = new WebSocket(wsUrl('/ws/tables/does_not_exist'));
36
+
37
+ ws.on('message', (message) => {
38
+ const parsed = JSON.parse(message.toString());
39
+ expect(parsed.message).toContain('does not exist');
40
+ });
41
+
42
+ ws.on('close', () => done());
43
+ });
44
+
45
+ it('rejects a connection with no access token when auth is enabled', (done) => {
46
+ const ws = new WebSocket(wsUrl('/ws/tables/users'));
47
+
48
+ ws.on('message', (message) => {
49
+ const parsed = JSON.parse(message.toString());
50
+ expect(parsed.message).toContain('Missing access token');
51
+ });
52
+
53
+ ws.on('close', () => done());
54
+ });
55
+
56
+ it('rejects a connection with an invalid access token', (done) => {
57
+ const ws = new WebSocket(wsUrl('/ws/tables/users'), {
58
+ headers: { Cookie: 'accessToken=not-a-valid-token' },
59
+ });
60
+
61
+ ws.on('message', (message) => {
62
+ const parsed = JSON.parse(message.toString());
63
+ expect(parsed.message).toContain('Invalid access token');
64
+ });
65
+
66
+ ws.on('close', () => done());
67
+ });
68
+
69
+ it('accepts a connection with a valid superuser access token', async () => {
70
+ const token = await generateToken(
71
+ { username: 'John', isSuperuser: true },
72
+ config.tokenSecret,
73
+ '1H',
74
+ );
75
+
76
+ const ws = new WebSocket(wsUrl('/ws/tables/users'), {
77
+ headers: { Cookie: `accessToken=${token}` },
78
+ });
79
+
80
+ const message = await new Promise((resolve) => {
81
+ ws.on('message', (msg) => resolve(JSON.parse(msg.toString())));
82
+ });
83
+
84
+ expect(message.message).toContain('Subscribed to table "users"');
85
+ ws.close();
86
+ });
87
+
88
+ it('broadcasts an INSERT to a subscribed client', async () => {
89
+ const token = await generateToken(
90
+ { username: 'John', isSuperuser: true },
91
+ config.tokenSecret,
92
+ '1H',
93
+ );
94
+
95
+ const ws = new WebSocket(wsUrl('/ws/tables/users'), {
96
+ headers: { Cookie: `accessToken=${token}` },
97
+ });
98
+
99
+ // wait for the subscription confirmation before triggering the insert
100
+ await new Promise((resolve) => ws.on('message', resolve));
101
+
102
+ const broadcastPromise = new Promise((resolve) => {
103
+ ws.on('message', (msg) => resolve(JSON.parse(msg.toString())));
104
+ });
105
+
106
+ await supertest(app)
107
+ .post('/api/tables/users/rows')
108
+ .set('Cookie', [`accessToken=${token}`])
109
+ .send({ fields: { firstName: 'Broadcast', lastName: 'Test' } });
110
+
111
+ const broadcastMessage = await broadcastPromise;
112
+
113
+ expect(broadcastMessage.type).toBe('INSERT');
114
+ expect(broadcastMessage.data).toMatchObject({
115
+ firstName: 'Broadcast',
116
+ lastName: 'Test',
117
+ });
118
+
119
+ ws.close();
120
+ });
121
+ });
package/.eslintignore DELETED
@@ -1,2 +0,0 @@
1
- *.test.js
2
- _extensions/
package/.eslintrc.js DELETED
@@ -1,24 +0,0 @@
1
- module.exports = {
2
- env: {
3
- node: true,
4
- commonjs: true,
5
- es2021: true,
6
- jest: true,
7
- },
8
- extends: ["eslint:recommended", "prettier"],
9
- overrides: [
10
- {
11
- env: {
12
- node: true,
13
- },
14
- files: [".eslintrc.{js,cjs}"],
15
- parserOptions: {
16
- sourceType: "script",
17
- },
18
- },
19
- ],
20
- parserOptions: {
21
- ecmaVersion: "latest",
22
- },
23
- rules: {},
24
- };
@@ -1,13 +0,0 @@
1
- // including the method, url, status code and response time
2
- const logger = (req, res, next) => {
3
- const start = Date.now();
4
- res.on('finish', () => {
5
- const delta = Date.now() - start;
6
- console.log(`${req.method} ${req.url} ${res.statusCode} ${delta}ms`);
7
- });
8
- next();
9
- };
10
-
11
- module.exports = {
12
- logger,
13
- };