-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
102 lines (86 loc) · 2.44 KB
/
server.js
File metadata and controls
102 lines (86 loc) · 2.44 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
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
97
98
99
100
101
102
const process = require('process');
const express = require('express');
const Knex = require('knex');
const app = express();
app.enable('trust proxy');
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(express.json());
const knex = connect();
function connect() {
const config = {
user: process.env.SQL_USER,
password: process.env.SQL_PASSWORD,
database: process.env.SQL_DATABASE
};
if (process.env.INSTANCE_CONNECTION_NAME && process.env.NODE_ENV === 'production') {
config.socketPath = `/cloudsql/${process.env.INSTANCE_CONNECTION_NAME}`;
}
// Connect to the database
const knex = Knex({
client: 'mysql',
connection: config
});
return knex;
}
//get all the courts
app.get("/api/create/:id", function (req, res) {
const tableName = req.params.id;
knex.schema.createTable(tableName,
(table) => {
table.increments('id');
table.string('name');
})
.then(() => {
console.log(`Successfully created ${tableName} table.`);
})
.catch((err) => {
console.error(`Failed to create ${tableName} table:`, err);
if (knex) {
knex.destroy();
}
});
res.send("done")
})
//post
app.post("/api/add/courts", function (req, res) {
knex('courts')
.insert({ ...req.body })
.then(() => {
console.log(`Successful insert.`);
})
.catch((err) => {
console.error(`Failed to insert:`, err);
if (knex) {
knex.destroy();
}
});
res.json("done")
})
app.get("/api/info/:name", function (req, res) {
knex
.from('courts')
.select('id', 'name')
.where('name', req.params.name)
.then(results => {
console.log(results)
res.json(results);
})
});
app.get("/api/courts", (req, res) => {
knex
.from('courts')
.select('name', 'image', 'comments').then(results => {
console.log(results)
console.log(JSON.stringify(results))
res.json(results);
})
})
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});