generated from ApplebaumIan/tu-cis-4398-docs-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
boilerplate.js
350 lines (309 loc) · 8.87 KB
/
boilerplate.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/**
* @module boilerplate
*/
const path = require('path');
const fs = require('fs').promises;
const decache = require('decache'); // Allow us to reload code via require
const multer = require('multer'); // File upload framework
const express = require('express'); // Web framework
const nunjucks = require('nunjucks'); // Templating engine
const expressWs = require('express-ws'); // WebSockets
const { Sequelize, DataTypes } = require('sequelize'); // DB connection/migrations
const { MoldyMeat } = require('moldymeat'); // "migrations"
const authMiddleware = require('./middleware/auth.js');
const cookieParser = require('cookie-parser');
const asyncHandler = require('express-async-handler');
const debounce = require('debounce');
const dotenv = require('dotenv');
dotenv.config();
/*
TODO:
- code reloading for routes
- code reloading for models
*/
/**
* The settings Express.js uses to serve HTTP
* @type {object}
* @property {number} port - The port the server binds to
*/
const settings = {
port: process.env.PORT ?? 5000, // port the webapp listens on
watchTemplates: false,
cacheTemplates: process.env.CACHE_TEMPLATES ? process.env.CACHE_TEMPLATES === 'true' : false,
reloadCode: process.env.RELOAD_CODE ? process.env.RELOAD_CODE === 'true' : true,
uploadPath: process.env.UPLOAD_PATH ?? path.join(__dirname, '.uploads')
};
/**
* The connection parameters for connecting to the database.
* @type {object}
* @property {string} database Overridable via PGDATABASE
* @property {string} username Overridable via PGUSER
* @property {string} password Overridable via PGPASSWORD
* @property {string} host Overridable via PGHOST
*/
const databaseSettings = {
database: process.env.PGDATABASE ?? 'postgres',
username: process.env.PGUSER ?? 'postgres',
password: process.env.PGPASSWORD ?? 'postgres',
host: process.env.PGHOST ?? 'localhost',
logging: process.env.LOGGING === 'false' ? false : console.log,
};
/**
* List of files to avoid watching.
*/
const watchIgnoreFiles = [
'boilerplate.js',
'models.js',
'index.js',
'webpack.config.js'
];
async function waitForCodeChange() {
return new Promise((resolve, reject) => {
let finish = debounce(resolve, 200);
let x = fs.watch(__dirname, {persistent: true}, (eventType, filename) => {
let shouldReload = filename.endsWith('.js');
shouldReload = shouldReload && !filename.endsWith('.test.js');
shouldReload = shouldReload && !watchIgnoreFiles.includes(filename);
if (shouldReload) {
x.unref();
finish(filename);
}
});
});
}
function requireUncached(mod) {
if (typeof jest !== 'undefined') {
jest.resetModules();
} else {
decache(mod);
}
return require(mod);
}
/**
* Create middleware to render nunjucks templates.
* @param {Express} app The express app you're adding things to.
* @return {function} Middleware function
*/
function nunjucksMiddleware(app) {
// Configure expressjs to use nunjucks when rendering html.
const env = nunjucks.configure(path.join(__dirname, 'templates'), {
autoescape: true,
watch: settings.watchTemplates,
throwOnUndefined: true,
noCache: !settings.cacheTemplates,
express: app
});
env.addFilter('json', function(value, spaces) {
if (value instanceof nunjucks.runtime.SafeString) {
value = value.toString();
}
const jsonString = JSON.stringify(value, null, spaces).replace(/</g, '\\u003c');
return nunjucks.runtime.markSafe(jsonString);
});
return function(req, res, next) {
env.addGlobal('authUser', req.user ?? null);
next();
};
}
/**
* Sleeps.
* @param {integer} ms How many milliseconds to sleep for.
* @async
*/
async function sleep(ms) {
return new Promise(x => setTimeout(x, ms));
}
/**
* Creates a database on the database server if it exists.
* @param {string} dbname The name of the database to create
* @async
*/
async function createDatabaseIfNotExists(dbname) {
const {database, ...settings} = databaseSettings;
const s = new Sequelize({
dialect: 'postgres',
...settings,
});
try {
await s.getQueryInterface().createDatabase(dbname);
} catch (e) {
if (e.name !== 'SequelizeDatabaseError') {
throw e;
}
} finally {
await s.close();
}
}
/**
* Drops a database from the database server if it exists.
* @param {string} dbname The name of the database to drop
* @async
*/
async function dropDatabaseIfExists(dbname) {
const {database, ...settings} = databaseSettings;
const s = new Sequelize({
dialect: 'postgres',
...settings,
});
try {
await s.getQueryInterface().dropDatabase(dbname);
} catch (e) {
if (e.name !== 'SequelizeDatabaseError') {
throw e;
}
} finally {
await s.close();
}
}
/**
* Initializes a sequelize instance. Loads models and syncs the database schema.
* @return {Sequelize} An instance of Sequelize that's ready to use.
* @async
*/
async function initSequelize(databaseName = null) {
const s = new Sequelize({
dialect: 'postgres',
...databaseSettings,
database: databaseName ?? databaseSettings.database
});
try {
await s.authenticate();
} catch (error) {
console.log("Unable to connect to the database: ");
console.log(error.message);
process.exit(1);
}
await loadModels(s);
await syncDatabase(s);
return s;
}
/**
* Loads model definitions
* @param {Sequelize} sequelize The Sequelize instance to use
* @returns {object} The models defined
* @async
*/
async function loadModels(sequelize) {
return requireUncached('./models')(sequelize);
}
/**
* Ensures the database tables match the models.
* @param {Sequelize} sequelize The Sequelize instance to use
* @async
*/
async function syncDatabase(sequelize) {
// await sequelize.sync();
const moldyMeat = new MoldyMeat({sequelize});
await moldyMeat.initialize();
await moldyMeat.updateSchema();
}
// middleware to respond to errors with page
function handleError(err, req, res, next) {
console.error(err);
res.status(500);
res.render('error.html', {error: err});
next();
}
/**
* Builds an expressjs app
* @returns {object} An Express.js app
*/
function buildExpressApp(sequelize) {
const uploadStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, settings.uploadPath);
},
filename: (req, file, cb) => {
const as = file.originalname.split('.');
let ext = as.pop();
ext = ext ? `.${ext}` : '';
cb(null, `${as.join('.')}.${Math.round(Math.random() * 1E9)}${ext}`);
}
});
const multerUpload = multer({storage: uploadStorage});
const app = express();
app.wsInstance = expressWs(app, undefined, {wsOptions: {clientTracking: true}});
app.upload = multerUpload;
app.use(handleError);
app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(cookieParser());
app.use(authMiddleware(sequelize.models.User));
app.use(nunjucksMiddleware(app));
requireUncached('./routes')(app, sequelize.models, sequelize);
app.use('/uploads', express.static(settings.uploadPath)); // serve files
app.use('/public', express.static(path.join(__dirname, "public")));
app.use('/webpack', express.static(path.join(__dirname, "webpack/dist")));
return app;
}
/**
* Starts the Express.js HTTP server.
* @async
*/
async function startServer() {
const uploadExists = await fs.access(settings.uploadPath).then(() => true, () => false);
if (!uploadExists) {
await fs.mkdir(settings.uploadPath, {recursive: true});
}
const sequelize = await initSequelize();
const runServer = async (mainSilent = false) => {
const app = buildExpressApp(sequelize);
// Starts the web server.
const server = await app.listen(settings.port);
if (!mainSilent) console.log(`tool-node is running on port ${settings.port}`);
const shutDown = (silent = false) => new Promise((resolve, reject) => {
if (!silent) console.log(`shutting down tool-node`);
server.closeAllConnections();
server.close(() => {
if (!silent) console.log(`successfully shut down tool-node`);
resolve();
});
});
return shutDown;
}
let stopServer = null;
if (settings.reloadCode) {
stopServer = await runServer();
while (true) {
const changedFile = await waitForCodeChange();
console.log(`${changedFile} was modified, reloading`);
await stopServer(true);
stopServer = await runServer(true);
}
} else {
stopServer = await runServer();
}
const shutDown = () => stopServer().then(() => process.exit(0));
process.on('SIGTERM', shutDown);
process.on('SIGINT', shutDown);
}
/**
* Starts the Sequelize shell
* @async
*/
async function startShell() {
const sequelize = await initSequelize();
const repl = require('repl');
const replServer = repl.start({prompt: "tool-shed> ", useGlobal: true});
replServer.context.models = sequelize.models;
replServer.context.sequelize = sequelize;
replServer.context.boilerplate = {
startShell,
startServer,
initSequelize,
databaseSettings,
settings,
buildExpressApp,
createDatabaseIfNotExists
};
}
module.exports = {
startShell,
startServer,
initSequelize,
databaseSettings,
settings,
buildExpressApp,
createDatabaseIfNotExists,
dropDatabaseIfExists
}