-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.js
More file actions
52 lines (48 loc) · 1.8 KB
/
test.js
File metadata and controls
52 lines (48 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const { Pool } = require('pg');
function performTransaction() {
const pool = new Pool({
connectionString: 'postgres://postgres:1234@localhost:3000/mydatabase'
});
return pool.connect()
.then(client => {
return client.query('BEGIN')
.then(() => {
//fix any errors in the queries
return client.query('INSERT INTO user (name, email) VALUES ($1, $2)', ['farah', 'farah@example.com'])
.then(() => client.query('UPDATE accounts SET balance = balance - $1 WHERE user_id = $2', [100, 1]))
.then(() => client.query('UPDATE accounts SET balance = balance + $1 WHERE user_id = $2', [100, 2]))
.then(() => {
return client.query('INSERT INTO users (name, email) VALUES ($1, $2)', ['aya', 'aya@example.com'])
})
.then(() => client.query('COMMIT'))
.catch(err => {
client.query('ROLLBACK')
.then(() => {
console.log('Rollback');
})
.catch(() => {
console.error('Error rolling back transaction', err);
})
.finally(() => {
client.release();
});
});
})
.catch(err => {
console.error('Error beginning transaction', err);
client.release();
});
})
.catch(err => {
console.error('Error acquiring client from pool', err);
});
}
test('Transaction is successful', async () => {
await performTransaction();
const pool = new Pool({
connectionString: 'postgres://postgres:1234@localhost:3000/mydatabase'
});
const result = await pool.query('SELECT name FROM users');
expect(result.rows).toContainEqual({name: 'farah'});
expect(result.rows).toContainEqual({name: 'aya'});
});