-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcounter-postgres-pg.js
More file actions
34 lines (26 loc) · 978 Bytes
/
counter-postgres-pg.js
File metadata and controls
34 lines (26 loc) · 978 Bytes
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
var express = require('express');
var pg = require('pg');
var app = express();
app.use(function(req, res) {
pg.connect('postgres://localhost/counter', function(err, client, done) {
client.query('select * from counter limit 1', function(err, result) {
if (err)
throw err;
if (result.rows.length === 0) {
client.query('insert into counter (value) values($1)', [1], function(err, result) {
if (err)
throw err;
res.end("Value: 1");
});
} else {
var counter = result.rows[0];
client.query('update counter set value = value + 1 where id = $1', [counter.id], function(err, result) {
if (err)
throw err;
res.end("Value: " + (counter.value + 1));
});
}
});
});
});
app.listen(8080);