-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
104 lines (83 loc) · 2.95 KB
/
app.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
const express = require('express');
const path = require('path');
const gitana = require('gitana');
const cors = require('cors');
const r = require('./src/requests.js');
const util = require('./src/util.js');
// Loading Middlwares
const menuParser = require('./src/middleware/menuParser.js');
const breadcrumbParser = require('./src/middleware/breadcrumbParser.js');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());
// connect to Cloud CMS
// this looks for gitana.json in local directory
gitana.connect(function(err) {
if (err) {
console.log("");
console.log("There was a problem connecting to Cloud CMS");
console.log(err);
process.exit();
}
// read the master branch
this.datastore("content").readBranch("master").then(function() {
// bind controllers
bindControllers(this, app);
// start web server
app.set('port', process.env.PORT || 3000);
const server = app.listen(app.get('port'), function() {
console.log("");
console.log("---------------------------------------------------------");
console.log("Hello World (Express) is alive and kicking!");
console.log("");
console.log(" To view the sample menu, go to http://localhost:" + server.address().port + "/a-category");
console.log("");
});
});
});
const bindControllers = function(branch, app)
{
app.get('/main-menu', (req, res, next) => {
r.item(branch, 'main-menu').then(data => {
r.menuItems(branch, data.item[0]._qname).then(data => {
res.data = data;
next()
}).catch(() => {});
}).catch(() => {});
}, menuParser, (req, res, next) => {
res.json(res.data);
});
app.get('*', (req, res, next) => {
const slug = req.path.split('/').slice(-1)[0];
r.item(branch, slug).then(data => {
r.breadcrumb(branch, data.item[0]._qname).then(d => {
data.breadcrumb = d;
res.data = data;
if(data.item[0]._statistics['a:category-association_INCOMING'] > 0){
r.relatives(branch, data.item[0]._qname).then(d => {
data.items = d;
res.data = data;
next();
}).catch(() => {});
} else {next();}
}).catch(() => {});;
}).catch(() => {});
}, breadcrumbParser, (req, res, next) => {
res.json(res.data);
});
// catch 404
app.use((req, res, next) => {
res.json({error:{
message: "Page not found!",
error: {status:404, stack:""}
}});
});
// error handlers
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.json({error: {
message: err.message,
error: err
}});
});
};