-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
79 lines (67 loc) · 1.92 KB
/
Copy pathindex.js
File metadata and controls
79 lines (67 loc) · 1.92 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
require('dotenv').config({ path: './config.env' });
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const db = require('./queries')
const dbo = require('./db/conn')
const port = 3000
app.use(bodyParser.json())
app.use(
bodyParser.urlencoded({
extended: true,
})
)
app.get('/', (request, response) => {
response.json({ info: 'Node.js, Express, and Postgres API' })
})
app.get('/users', db.getUsers)
app.get('/user/:id', db.getUserById)
app.get('/search', db.findUsersBySearch)
app.post('/users', db.createUser)
app.put('/users/:id', db.updateUser)
app.delete('/users/:id', db.deleteUser)
app.get('/first_collection', async function (req, res) {
const dbConnect = dbo.getDb();
dbConnect
.collection("myFirstCollection")
.find({}).limit(50)
.toArray(function (err, result) {
if (err) {
res.status(400).send("Error fetching items from first collection!");
} else {
res.json(result);
}
});
});
app.post('/first_collection', function (req, res) {
const dbConnect = dbo.getDb();
// "firstName": "James",
// "surname": "Doe",
// "department": "IT"
const testDocument = {
firstName: req.body.firstName,
surname: req.body.surname,
department: req.body.department
};
dbConnect
.collection("myFirstCollection")
.insertOne(testDocument, function (err, result) {
if (err) {
res.status(400).send("Error inserting test document!");
} else {
console.log(`Added a new test document with id ${result.insertedId}`);
res.status(204).send();
}
});
});
// perform a database connection when the server starts
dbo.connectToServer(function (err) {
if (err) {
console.error(err);
process.exit();
}
// start the Express server
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
});