-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
182 lines (158 loc) · 5.61 KB
/
index.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
let express = require('express');
let app = express();
let http = require('http');
let server = http.Server(app);
const Sentry = require('@sentry/node');
const Tracing = require("@sentry/tracing");
let bodyParser = require("body-parser");
let morgan = require('morgan');
let mongoose = require("mongoose");
let Schema = mongoose.Schema;
let path = require("path");
let fs = require("fs");
let rfs = require("rotating-file-stream");
let Puller = require("express-git-puller").Puller;
let metrics = require("./metrics");
let config = require("./config");
let util = require("./util")
let port = process.env.PORT || config.port || 3012;
Sentry.init({
dsn: config.sentry.dsn,
integrations: [
new Sentry.Integrations.Http({tracing: true}),
new Tracing.Integrations.Express({
app: app
})
],
tracesSampleRate: 0.001,
serverName: config.server.name
});
app.use(Sentry.Handlers.requestHandler());
app.use(Sentry.Handlers.tracingHandler());
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
res.header("Access-Control-Allow-Headers", "X-Requested-With, Accept, Content-Type, Origin, Spiget-User-Agent");
res.header("Access-Control-Request-Headers", "X-Requested-With, Accept, Content-Type, Origin");
res.header("Access-Control-Expose-Headers", "Content-Type, Content-Length, Location, X-Api-Time, X-Api-Server, X-Page-Sort, X-Page-Order, X-Page-Size, X-Max-Page-Size, X-Page-Index, X-Page-Count");
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
} else {
return next();
}
});
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json({extended: true}));
app.use(metrics.apiRequestsMiddleware);
app.use(function (req, res, next) {
req.realAddress = req.header("x-real-ip") || req.realAddress;
res.header("X-Spiget-Server", config.server.name || "default");
next();
});
app.use("/.well-known", express.static(".well-known"));
// var swStats = require('swagger-stats');
// app.use(swStats.getMiddleware(config.swagger));
// create a rotating write stream
let accessLogStream = rfs('access.log', {
interval: '1d', // rotate daily
path: path.join(__dirname, 'log'),
compress: "gzip"
})
// setup the logger
app.use(morgan('combined', {stream: accessLogStream}))
morgan.token('remote-addr', function (req) {
return req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress;
});
// Pretty-Print JSON
app.set('json spaces', 2);
let updatingApp = false;
{// Git Puller
console.log("Setting up git puller");
const updateDelay = Math.ceil(Math.random() * 10000) + Math.ceil(Math.random() * 10000);
const puller = new Puller({
...{
events: ["push"],
branches: ["master"],
vars: {
appName: "spiget"
},
commandOrder: ["pre", "git", "install", "post"],
commands: {
git: [
"git fetch --all",
"git reset --hard origin/master"
],
install: [
"npm install"
],
post: [
"pm2 restart $appName$"
]
},
delays: {
pre: updateDelay,
install: Math.ceil(Math.random() * 200),
post: Math.ceil(Math.random() * 1000)
}
},
...config.puller
});
puller.on("before", (req, res) => {
console.log(`waiting ${ updateDelay }ms before updating`);
setTimeout(() => {
console.log("updating!")
updatingApp = true;
console.log(process.cwd());
}, updateDelay + 2000);
});
app.use(function (req, res, next) {
if (updatingApp) {
res.status(503).send({err: "app is updating"});
return;
}
next();
});
app.use(config.puller.endpoint, bodyParser.json({limit: '100kb'}), puller.middleware);
}
// mongoose.plugin(util.idPlugin);
mongoose.plugin(util.paginatePlugin);
require("./db/db")(mongoose, config);
app.get("/", function (req, res) {
res.redirect("/v2");
});
app.get("/health.json", function (req, res) {
res.json({"status": "I'm healthy, yay!"});
});
app.get("/v2", function (req, res) {
res.redirect("/v2/status");
});
app.use("/v2/status", require("./routes/status")(express, config));
app.use("/v2/resources", require("./routes/resources")(express, config));
app.use("/v2/authors", require("./routes/authors")(express, config));
app.use("/v2/categories", require("./routes/categories")(express, config));
app.use("/v2/reviews", require("./routes/reviews")(express, config));
app.use("/v2/search", require("./routes/search")(express, config));
app.use("/v2/metrics", require("./routes/metrics")(express, config));
app.use("/v2/webhook", require("./routes/webhook")(express, config));
app.use(Sentry.Handlers.errorHandler());
app.use(function (err, req, res, next) {
console.error(err);
res.status(500).json({
error: "Unexpected Exception",
msg: "Unexpected Exception. Please report this to https://github.com/SpiGetOrg/api.spiget.org/issues"
})
})
function exitHandler(err) {
if (err) {
console.log("\n\n\n\n\n\n\n\n");
console.log(err);
console.log("\n\n\n");
}
process.exit();
}
server.listen(port, function () {
console.log('listening on *:' + port);
});
process.on("exit", exitHandler);
process.on("SIGINT", exitHandler);
process.on("uncaughtException", exitHandler);