Skip to content

Commit 9c2b897

Browse files
authored
Merge pull request #211 from BritishYouthBandAssociation/refactor
Refactor
2 parents dde1ede + e4c7604 commit 9c2b897

14 files changed

+779
-1209
lines changed

WPOrderProcessor.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
const {
44
helpers: {
55
StringHelper
6-
}
6+
},
7+
constants
78
} = require(global.__lib);
89

910
class WPOrderProcessor {
@@ -51,7 +52,7 @@ class WPOrderProcessor {
5152
Name: StringHelper.toTitleCase(orgName),
5253
Slug: slug,
5354
Description: '',
54-
OrganisationTypeId: 1
55+
OrganisationTypeId: constants.ORGANISATION_TYPE.BAND
5556
};
5657

5758
let matchedOrg = await this.#db.Organisation.findOne({

app.js

+20-83
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,9 @@
11
'use strict';
22

33
// Import modules
4-
const express = require('express');
5-
const { engine } = require('express-handlebars');
6-
const fs = require('fs');
7-
const morgan = require('morgan');
84
const path = require('path');
9-
const serveFavicon = require('serve-favicon');
105
const session = require('express-session');
116
const SequelizeStore = require('connect-session-sequelize')(session.Store);
12-
const os = require('os');
13-
const formData = require('express-form-data');
147

158
// Initialise library path
169
const libPath = path.join(__dirname, process.env.LIB_PATH ?? '../Library');
@@ -20,80 +13,36 @@ global.__lib = libPath;
2013
const {
2114
helpers: {
2215
ConfigHelper,
23-
HandlebarsHelper
24-
}
16+
},
17+
Server,
18+
constants
2519
} = require(libPath);
2620

2721
//set global base dir
2822
global.__approot = __dirname;
2923

30-
/**
31-
* loadRoutes() Loads all of the routes from /routers into a map
32-
*
33-
* @return {Array<Array<String, Object>>} All of the routes
34-
*/
35-
function loadRoutes() {
36-
const routes = [];
37-
38-
const routeFiles = fs.readdirSync(path.join(__dirname, 'routes'))
39-
.filter(file => file.endsWith('.js'));
40-
41-
for (const file of routeFiles) {
42-
const route = require(path.join(__dirname, 'routes', file));
43-
routes.push([route.root, route.router]);
44-
}
45-
46-
return routes;
47-
}
48-
4924
async function main() {
5025
// Initialise express app
51-
const app = express();
26+
const app = Server({
27+
dir: __dirname
28+
});
5229

5330
// Import configuration
5431
const serverOptions = ConfigHelper.importJSON(path.join(__dirname, 'config'), 'server');
5532

5633
// Add logging middleware
5734
if (serverOptions.logging) {
58-
app.use(morgan('tiny', {
59-
// don't log out static files and unnecessary fluff
60-
skip: (req, res) => {
61-
return /(^\/(js|css|fonts|assets|favicon)|(png|jpg|css))/.test(req.path);
62-
}
63-
}));
35+
app.enableLogging('tiny', (req) => /(^\/(js|css|fonts|assets|favicon)|(png|jpg|css))/.test(req.path));
6436
}
6537

6638
// Set up handlebars templating engine
67-
app.engine(
68-
'hbs',
69-
engine({
70-
extname: '.hbs',
71-
helpers: HandlebarsHelper,
72-
runtimeOptions: {
73-
allowProtoPropertiesByDefault: true,
74-
allowProtoMethodsByDefault: true
75-
}
76-
})
77-
);
78-
app.set('view engine', 'hbs');
79-
app.set('views', path.join(__dirname, 'views'));
80-
81-
//allow file uploads
82-
app.use(formData.parse({
83-
uploadDir: os.tmpdir(),
84-
autoClean: true
85-
}));
86-
app.use(formData.format());
87-
88-
// Set up parsers to allow access to POST bodies
89-
app.use(express.json());
90-
app.use(express.urlencoded({
91-
extended: true
92-
}));
93-
94-
// Set up routes for static files
95-
app.use(serveFavicon(
96-
path.join(__dirname, 'public/assets/favicon.ico')));
39+
app.useHandlebars('hbs', {
40+
extname: '.hbs',
41+
runtimeOptions: {
42+
allowProtoPropertiesByDefault: true,
43+
allowProtoMethodsByDefault: true
44+
}
45+
});
9746

9847
// Serve the production vue script if in production environment
9948
app.get('/js/vue.js', (req, res, next) => {
@@ -104,17 +53,12 @@ async function main() {
10453
next();
10554
});
10655

107-
app.use(express.static(path.join(__dirname, 'public')));
56+
app.addStaticDir(path.join(__dirname, 'public'));
10857

10958
// Get database models and connection
11059
const dbPath = path.join(libPath, 'models');
11160
const db = await require(dbPath)(path.join(__dirname, 'config/db'));
112-
113-
//add global db
114-
app.use((req, res, next) => {
115-
req.db = db;
116-
next();
117-
});
61+
app.registerGlobals({db});
11862

11963
//... and use it for our session stuff too!
12064
const sessionStore = new SequelizeStore({ db: db.sequelize });
@@ -137,11 +81,7 @@ async function main() {
13781
return res.redirect(`/?next=${req.path}`);
13882
}
13983
} else {
140-
req.session.user = await req.db.User.findOne({
141-
where: {
142-
id: req.session.user.id
143-
}
144-
});
84+
req.session.user = await req.db.User.findByPk(req.session.user.id);
14585

14686
req.session.user.bands = await req.db.Organisation.findAll({
14787
include: [{
@@ -152,7 +92,7 @@ async function main() {
15292
attributes: []
15393
}],
15494
where: {
155-
OrganisationTypeId: 1 //we only want associated bands here
95+
OrganisationTypeId: constants.ORGANISATION_TYPE.BAND
15696
}
15797
});
15898

@@ -186,17 +126,14 @@ async function main() {
186126
next();
187127
});
188128

189-
// Add external routers to express
190-
for (const route of loadRoutes()) {
191-
app.use(route[0], route[1]);
192-
}
129+
app.loadRoutes();
193130

194131
/*
195132
* If the request gets to the bottom of the route stack, it doesn't
196133
* have a defined route and therefore a HTTP status code 404 is sent
197134
* and an error page shown
198135
*/
199-
app.use((req, res) => {
136+
app.use((_, res) => {
200137
res.status(404).render('error', {
201138
title: 'Error',
202139
code: 404,

gulpfile.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ function overwriteReadme(cb) {
109109
const readmePath = path.join(__dirname, 'README.md');
110110
const templatePath = path.join(__dirname, 'TEMPLATE_README.md');
111111

112-
if (!fs.existsSync(readmePath) | !fs.existsSync(templatePath)) {
112+
if (!fs.existsSync(readmePath) || !fs.existsSync(templatePath)) {
113113
return cb();
114114
}
115115

middleware.js

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
'use strict';
2+
3+
function resolveDynamicAccessor(object, accessor){
4+
if (typeof accessor == 'string'){
5+
return object[accessor];
6+
}
7+
8+
for (let i = 0; i < accessor.length; i++){
9+
object = object[accessor[i]];
10+
11+
if (object == null){
12+
return null;
13+
}
14+
}
15+
16+
return object;
17+
}
18+
19+
module.exports = {
20+
checkAdmin(req, res, next){
21+
if (!req.session.user.IsAdmin) {
22+
return res.redirect('/no-access');
23+
}
24+
25+
next();
26+
},
27+
28+
matchingID(paramProp, sessionProp){
29+
return (req, res, next) => {
30+
const id = resolveDynamicAccessor(req.params, paramProp);
31+
const valueToCheck = resolveDynamicAccessor(req.session, sessionProp);
32+
33+
if (id != valueToCheck && !req.session.user.IsAdmin){
34+
return res.redirect('/no-access');
35+
}
36+
37+
next();
38+
};
39+
}
40+
};

routes/api.js

+7-44
Original file line numberDiff line numberDiff line change
@@ -38,16 +38,8 @@ router.get('/organisation', validator.query(Joi.object({
3838
router.get('/organisation/search', validator.query(Joi.object({
3939
q: Joi.string()
4040
.required()
41-
})), async (req, res, next) => {
42-
const orgs = await req.db.Organisation.findAll({
43-
include: [req.db.OrganisationType],
44-
where: {
45-
Name: {
46-
[req.db.Sequelize.Op.like]: `%${req.query.q}%`
47-
}
48-
}
49-
});
50-
41+
})), async (req, res) => {
42+
const orgs = await req.db.Organisation.search(req.query.q);
5143
res.json(orgs);
5244
});
5345

@@ -65,24 +57,7 @@ router.get('/membership/:season', validator.query(Joi.object({
6557
where.MembershipTypeId = req.query.type;
6658
}
6759

68-
const members = await req.db.Membership.findAll({
69-
include: [
70-
req.db.Label,
71-
req.db.MembershipType,
72-
{
73-
model: req.db.IndividualMembership,
74-
include: [req.db.User]
75-
},
76-
{
77-
model: req.db.OrganisationMembership,
78-
include: {
79-
model: req.db.Organisation,
80-
include: [req.db.OrganisationType]
81-
}
82-
}
83-
],
84-
where: where
85-
});
60+
const members = await req.db.Membership.getAll(where);
8661

8762
res.json(members);
8863
});
@@ -100,24 +75,12 @@ router.get('/caption/:id/judges/search', validator.query(Joi.object({
10075
return next();
10176
}
10277

103-
const judges = await req.db.User.findAll({
104-
include: [{
105-
model: req.db.Caption,
106-
where: {
107-
id: caption.id
108-
}
109-
}],
78+
const judges = await req.db.User.searchByName(req.query.q, [{
79+
model: req.db.Caption,
11080
where: {
111-
[Op.or]: {
112-
FirstName: {
113-
[Op.like]: `%${req.query.q}%`
114-
},
115-
Surname: {
116-
[Op.like]: `%${req.query.q}%`
117-
}
118-
}
81+
id: caption.id
11982
}
120-
});
83+
}]);
12184

12285
res.json(judges);
12386
});

routes/config.js

+4-22
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,7 @@ const validator = require('@byba/express-validator');
88

99
const router = express.Router();
1010

11-
const checkAdmin = (req, res, next) => {
12-
if (!req.session.user.IsAdmin) {
13-
return res.redirect('/no-access');
14-
}
15-
16-
next();
17-
};
11+
const {checkAdmin} = require('../middleware');
1812

1913
router.get('/', checkAdmin, (req, res) => {
2014
const sections = ['Membership Type', 'Organisation Type', 'Event Type', 'Payment Type', 'Division', 'Caption', 'Season'];
@@ -158,11 +152,8 @@ router.get('/event-type', checkAdmin, validator.query(Joi.object({
158152
['id'],
159153
[req.db.EventTypeDiscount, 'DiscountAfter']
160154
]
161-
}), req.db.MembershipType.findAll({
162-
where: {
163-
IsOrganisation: true,
164-
IsActive: true
165-
}
155+
}), req.db.MembershipType.getActive({
156+
IsOrganisation: true
166157
})]);
167158

168159
return res.render('config/event-type.hbs', {
@@ -433,16 +424,7 @@ router.get('/season', checkAdmin, validator.query(Joi.object({
433424
next: Joi.string(),
434425
needsSeason: Joi.boolean()
435426
})), async (req, res) => {
436-
const season = await req.db.Season.findOne({
437-
where: {
438-
Start: {
439-
[Op.lte]: Date.now()
440-
},
441-
End: {
442-
[Op.gte]: Date.now()
443-
}
444-
}
445-
});
427+
const season = await req.db.Season.getCurrent();
446428

447429
const others = await req.db.Season.findAll({
448430
where: {

0 commit comments

Comments
 (0)