-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.js
133 lines (102 loc) · 2.36 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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
const expressLayouts = require("express-ejs-layouts");
require('dotenv').config();
const express = require("express");
const app = express();
// Firebase Node.js Admin SDK
const firebase = require("firebase-admin");
const key = {
"type": process.env.TYPE,
"project_id": process.env.PROJECT_ID,
"private_key_id": process.env.PRIVATE_KEY_ID,
"private_key": process.env.PRIVATE_KEY.replace(/\\n/g, "\n"),
"client_id": process.env.CLIENT_ID,
"client_email": process.env.CLIENT_EMAIL,
"auth_uri": process.env.AUTH_URI,
"token_uri": process.env.TOKEN_URI,
"auth_provider_x509_cert_url": process.env.AUTH_PROVIDER,
"client_x509_cert_url": process.env.CLIENT_URL
}
//Initialize Firebase app
firebase.initializeApp({
credential: firebase.credential.cert(key),
databaseURL: process.env.DB_URL
});
// Firebase products used
const firestore = firebase.firestore();
// Middleware
// Static folder to serve css and js
app.use("/public", express.static(__dirname + "/public"));
// ejs
app.use(expressLayouts);
app.set("view engine", "ejs");
// Body parser
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
//Routes
app.use("/restaurant", require("./routes/restaurant.js"));
app.use("/endpoints", require("./routes/endpoints.js"));
app.get
(
"/",
async (req, res) =>
{
const restaurants = await firestore
.collection("restaurants")
.orderBy("name", "asc")
.get()
.then
(
(querySnapshot) =>
{
let restaurantArr = []
querySnapshot.forEach
(
(restaurant) => restaurantArr.push({ id: restaurant.id, ...restaurant.data() })
);
return restaurantArr;
}
);
res.render("home-page", { restaurants });
}
);
// Error handlers
app.use
(
(req, res, next) =>
{
let err = new Error('Not Found');
err.status = 404;
err.message = `Requested URL "${req.url}" was not found`;
next(err);
}
);
app.use
(
(err, req, res, next) =>
{
if(err.status === 404)
var status_descp = "NOT FOUND";
else if(!err.status)
{
err.status = 500;
status_descp = "INTERNAL SERVER ERROR";
}
res.status(err.status);
res.render('error', {
status: err.status,
status_descp: status_descp,
err_trace: err
});
}
);
const PORT = process.env.PORT || 5000;
app.listen
(
PORT,
(err) =>
{
if(err)
console.log(err);
console.log(`Server started on port ${PORT}...`);
}
);