-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.mjs
96 lines (75 loc) · 2.54 KB
/
app.mjs
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import express from 'express';
import PG from 'pg';
import bodyParser from 'body-parser';
const app = express();
async function devPostgres() {
console.log('Starting Postgres');
const TestContainers = await import('testcontainers');
const pgPassword = Math.random().toString(36).substring(2);
const container = await new TestContainers.default.GenericContainer('postgres')
.withExposedPorts(5432)
.withTmpFs({'/temp_pgdata': 'rw,noexec,nosuid,size=65536k'})
.withEnv('POSTGRES_PASSWORD', pgPassword)
.start();
console.log('Postgres Started');
async function stop(signal) {
console.log('Stopping Postgres');
await container.stop();
process.kill(process.pid, signal);
}
process.once('SIGUSR2', stop);
process.once('SIGINT', stop);
process.once('SIGTERM', stop);
return {
host: container.getHost(),
port: container.getMappedPort(5432),
user: 'postgres',
password: pgPassword,
database: 'postgres'
}
}
async function getConnectionInfo() {
if (process.env.DB_USER && process.env.DB_PASS && process.env.DB_NAME && process.env.CLOUD_SQL_CONNECTION_NAME) {
return {
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
host: `/cloudsql/${process.env.CLOUD_SQL_CONNECTION_NAME}`
};
}
else if (process.env.NODE_ENV === 'production') {
app.get('/', (req, res) => res.send("App Needs Setup"));
return null;
}
else {
return await devPostgres();
}
}
async function getPool() {
const pool = new PG.Pool(await getConnectionInfo());
await pool.query('SELECT * FROM bar').catch(async error => {
if (error.message === 'relation "bar" does not exist') {
console.log('Creating Schema from schema.sql');
const fs = await import('fs');
const schema = fs.readFileSync('schema.sql', 'utf8');
await pool.query(schema);
console.log('Schema created');
}
});
return pool;
}
const pool = await getPool();
// order is important because non-setup apps needs to register a get / handler before these run
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.enable('trust proxy');
app.get('/bars', async (req, res) => {
const result = await pool.query('SELECT * FROM bar');
res.json(result.rows);
});
app.post('/bars', async (req, res) => {
const result = await pool.query('INSERT INTO bar(name) VALUES($1)', [req.body.name]);
res.redirect('/');
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}`));