Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
82 lines (72 loc) · 2.71 KB
/
Copy pathapp.js
File metadata and controls
82 lines (72 loc) · 2.71 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
var express = require('express');
var favicon = require('serve-favicon');
require('dotenv').config();
var app = express();
app.use(favicon(__dirname + '/public/images/favicon.ico'));
app.use(express.static('./public'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
/* ejs */
app.set('views', './views');
app.set('view engine', 'ejs');
/* firebase admin SDK */
var admin = require('firebase-admin');
var serviceAccount = require(process.env.serviceAccount); // private key store in the root folder
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: process.env.firebaseURL
});
var fbData = admin.database();
/* routers */
app.get('/', (req, res) => {
var appProperties, comments = [], sum = 0; // 準備要給client的東西
fbData.ref('appProperties').once('value', (snapshot) => {
appProperties = snapshot.val(); // 取得appProperties資料後
}).then(() => {
fbData.ref('comments/public').orderByChild('unixTime').once('value', (snapshot) => {
snapshot.forEach((item) => {
comments.push(item.val()); // 再一個個取得public comment,push到comments陣列內
sum++;
});
comments.reverse(); // comments陣列的順序是unixTime小到大,反轉陣列變成大到小
var allData = {
'appProperties': appProperties,
'comments': comments,
'sum': sum
}; // 整理成json格式
res.render('index', allData); // 最後導向頁面
});
});
});
/* 當使用者POST */
app.post('/submitted', (req, res) => {
/* 表單資訊 */
var nickname = req.body.nickname;
var content = req.body.content;
var isPrivate = req.body.isPrivate;
var time = req.body.time;
var unixTime = req.body.unixTime;
/* 根據isPrivate決定存放位置 */
if (isPrivate) {
var commentRef = fbData.ref(process.env.privatePosition).push();
updateTask();
} else {
var commentRef = fbData.ref(process.env.publicPosition).push();
updateTask();
}
function updateTask() {
commentRef.set({ 'nickname': nickname, 'content': content, 'isPrivate': isPrivate, 'time': time, 'unixTime': unixTime }).then(() => {
fbData.ref(process.env.publicPosition).orderByChild('unixTime').once('value', (snapshot) => {
var comments = [];
snapshot.forEach((item) => {
comments.push(item.val());
});
comments.reverse();
res.send(comments);
});
});
}
});
/* port listening */
var port = process.env.PORT || 3000;
app.listen(port);