-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
74 lines (52 loc) · 1.76 KB
/
server.js
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
import express, { json } from 'express'
import morgan from 'morgan';
import cors from 'cors'
import { config } from 'dotenv';
import router from './router/routes.js';
import { connect } from 'mongoose';
const app = express()
// middleware
app.use(morgan('dev')) // logging
app.use(cors())
app.use(json()) // returns middleware that only parses json and only looks at requests where the Content-Type header matches the type option.
config({ path: '.env' }) // Loads .env file contents into process.env.
/**
* @description : creating the first route for testing and config for PORT listen
*/
app.get('/', (req, res) => {
try {
res.json('200 GET Success')
} catch (error) {
res.json(error)
}
})
const PORT = process.env.PORT || 8080
// api routes
app.use('/api/v1', router)
// database connection
import mongoose from "mongoose";
mongoose.set('strictQuery', false);
import { MongoClient, ServerApiVersion } from 'mongodb';
const uri = process.env.MONGO_URI;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
}).then(() => {
console.log('Database Connected success!')
}).catch(error => {
console.error(error);
});
mongoose.connect(uri)
// connect().then(()=>{
// try {
// } catch (error) {
// console.log('Error while connecting to server')
// }
// }).catch(error => {
// console.error('Error while connecting to Database');
// })
app.listen(PORT, () => {
console.log(`Server running on localhost:${PORT}`)
})