Add eslint rule: max line length (80)

Signed-off-by: Fred Boniface <fred@fjla.uk>
This commit is contained in:
Fred Boniface 2023-06-07 21:53:56 +01:00
parent 66b2ba002b
commit 849c31af36
11 changed files with 67 additions and 39 deletions

View File

@ -1,6 +1,7 @@
module.exports = { module.exports = {
'env': { 'env': {
'browser': true, 'browser': false,
'node': true,
'commonjs': true, 'commonjs': true,
'es2021': true 'es2021': true
}, },

View File

@ -15,7 +15,8 @@ module.exports = async function authCheck(req, res, next) {
if (!result) { if (!result) {
const err = new Error('Unauthorised'); const err = new Error('Unauthorised');
err.status = 401; err.status = 401;
log.out('authMiddlewares: Authentication attempted with incorrect key', 'warn'); log.out('authMiddlewares: Authentication attempted with incorrect key',
'warn');
return next(err); return next(err);
} else { } else {
log.out('authMiddlewares: User authenticated', 'dbug'); log.out('authMiddlewares: User authenticated', 'dbug');

View File

@ -1,5 +1,4 @@
/* eslint-disable no-useless-escape */ /* eslint-disable no-useless-escape */
/* global process */
const axios = require('axios'); const axios = require('axios');
const log = require('../utils/log.utils'); const log = require('../utils/log.utils');
@ -20,12 +19,13 @@ async function sendToGitea(body) {
} }
}; };
var res = await axios.post(url, body, opts); var res = await axios.post(url, body, opts);
// Need to read the output from the POST and pass the result upwards to the client. /* Need to read the output from the POST and pass the result upwards to the
client.*/
if (res.status == 201) { if (res.status == 201) {
log.out('issueService.sendToGitea: Issue sent to Gitea', 'info'); log.out('issueService.sendToGitea: Issue sent to Gitea', 'info');
return {status: res.status,message:'issue created'}; return {status: res.status,message:'issue created'};
} else { } else {
log.out(`issueService.sendToGitea: Failed to send issue to Gitea: ${res.body}`, 'err'); log.out(`issueService.sendToGitea: Fail to send issue: ${res.body}`, 'err');
return {status: res.status,message:'issue not created'}; return {status: res.status,message:'issue not created'};
} }
} }

View File

@ -1,4 +1,3 @@
/* global process */
// Parse and return an LDB Request // Parse and return an LDB Request
const log = require('../utils/log.utils'); // Log Helper const log = require('../utils/log.utils'); // Log Helper
@ -27,12 +26,14 @@ async function get(id, staff=false){
} }
} catch (err) { } catch (err) {
log.out(`ldbService.get: Error, Unable to find CRS: ${err}`, 'info'); log.out(`ldbService.get: Error, Unable to find CRS: ${err}`, 'info');
return {ERROR:'NOT_FOUND',description:'The entered station was not found. Please check and try again.'}; return {
ERROR:'NOT_FOUND',
description:'The entered station was not found.'};
} }
} }
async function arrDepBoard(CRS){ async function arrDepBoard(CRS){
log.out(`ldbService.arrDepBoard: Trying to fetch ArrDep Board for ${CRS}`, 'info'); log.out(`ldbService.arrDepBoard: Trying to fetch board for ${CRS}`, 'info');
try { try {
const options = { const options = {
numRows: 10, numRows: 10,
@ -42,12 +43,15 @@ async function arrDepBoard(CRS){
return await api.call('GetArrDepBoardWithDetails', options, false, false); return await api.call('GetArrDepBoardWithDetails', options, false, false);
} catch (err) { } catch (err) {
log.out(`ldbService.arrDepBoard: Lookup Failed for: ${CRS}`, 'warn'); log.out(`ldbService.arrDepBoard: Lookup Failed for: ${CRS}`, 'warn');
return {GetStationBoardResult: 'not available', Reason: `The CRS code ${CRS} is not valid`, Why: 'Sometimes a station will have more than one CRS - for example Filton Abbey Wood has FIT and FAW however schedules are only available when looking up with FIT - this is how the National Rail Enquiries systems work.'}; return {
GetStationBoardResult: 'not available',
Reason: `The CRS code ${CRS} is not valid`
};
} }
} }
async function arrDepBoardStaff(CRS) { async function arrDepBoardStaff(CRS) {
log.out(`ldbService.arrDepBoardStaff: Trying to fetch ArrDep Board for ${CRS}`, 'dbug'); log.out(`ldbService.arrDepBoardStaff: Try to fetch board for ${CRS}`, 'dbug');
try { try {
const options = { const options = {
numRows: 25, numRows: 25,
@ -58,7 +62,10 @@ async function arrDepBoardStaff(CRS) {
return await api.call('GetArrDepBoardWithDetails', options, false, false); return await api.call('GetArrDepBoardWithDetails', options, false, false);
} catch (err) { } catch (err) {
log.out(`ldbService.arrDepBoardStaff: Lookup Failed for: ${CRS}, "warn`); log.out(`ldbService.arrDepBoardStaff: Lookup Failed for: ${CRS}, "warn`);
return {GetStationBoardResult: 'not available', Reason: `The CRS code ${CRS} is not valid`, Why: 'Sometimes a station will have more than one CRS - for example Filton Abbey Wood has FIT and FAW however schedules are only available when looking up with FIT - this is how the National Rail Enquiries systems work.'}; return {
GetStationBoardResult: 'not available',
Reason: `The CRS code ${CRS} is not valid`
};
} }
} }

View File

@ -1,4 +1,3 @@
/* global process */
const log = require('../utils/log.utils'); const log = require('../utils/log.utils');
const mail = require('nodemailer'); //>> Probs wrong const mail = require('nodemailer'); //>> Probs wrong
@ -18,7 +17,9 @@ let transporter = mail.createTransport({
} }
}); });
async function send(message){ // message is an object containing strings for: *to, cc, bcc, *subject, *txt, html (* denotes required) /* 'message' is an object containing string values for:
*to, cc, bcc, *subject, *txt, html. * denotes required */
async function send(message) {
log.out('mailServices.send: Message send request received', 'info'); log.out('mailServices.send: Message send request received', 'info');
message.from = fromAddr; message.from = fromAddr;
try { try {

View File

@ -8,8 +8,8 @@ const errors = require('../configs/errorCodes.configs');
async function createRegKey(body) { async function createRegKey(body) {
log.out('registerServices.createRegKey: Incoming request', 'INFO'); log.out('registerServices.createRegKey: Incoming request', 'INFO');
const domain = await clean.getDomainFromEmail(body.email); // The function should validate the email const domain = await clean.getDomainFromEmail(body.email);
log.out(`registerServices: New registration request from domain: ${domain}`, 'info'); log.out(`registerServices: Registration request from: ${domain}`, 'info');
if (domains.includes(domain)) { if (domains.includes(domain)) {
log.out(`registerServices.createRegKey: Key from valid domain: ${domain}`); log.out(`registerServices.createRegKey: Key from valid domain: ${domain}`);
const uuid = await auth.generateKey(); const uuid = await auth.generateKey();
@ -17,7 +17,7 @@ async function createRegKey(body) {
const message = await auth.generateConfirmationEmail(body.email, uuid); const message = await auth.generateConfirmationEmail(body.email, uuid);
if (!message) { if (!message) {
const err = new Error('Message generation error'); const err = new Error('Message generation error');
log.out('registerServices.createRegKey: Error generating registration email', 'err'); log.out('registerServices.createRegKey: Error generating email', 'err');
log.out(err, 'err'); log.out(err, 'err');
return 500; return 500;
} }
@ -31,9 +31,9 @@ async function createRegKey(body) {
async function regUser(req) { // Add input validation async function regUser(req) { // Add input validation
log.out(`Read UUID: ${req.uuid}`, 'dbug'); log.out(`Read UUID: ${req.uuid}`, 'dbug');
log.out(`registrationServices.regUser: Checking validity of : ${req.uuid}`, 'info'); log.out(`registrationServices.regUser: Request from: ${req.uuid}`, 'info');
const res = await auth.checkRequest(req.uuid); const res = await auth.checkRequest(req.uuid);
log.out(`registrationServices.regUser: checkRequest returned: ${JSON.stringify(res)}`, 'info'); log.out(`registrationServices.regUser: ${JSON.stringify(res)}`, 'info');
if (res.result) { if (res.result) {
const uuid = await auth.generateKey(); const uuid = await auth.generateKey();
const apiKey = await db.addUser(uuid, res.domain); const apiKey = await db.addUser(uuid, res.domain);

View File

@ -5,7 +5,8 @@ const pis = require('../services/pis.services');
async function findByHeadcodeToday(headcode) { async function findByHeadcodeToday(headcode) {
const sanitizedHeadcode = clean.removeNonAlphanumeric(headcode).toUpperCase(); const sanitizedHeadcode = clean.removeNonAlphanumeric(headcode).toUpperCase();
log.out(`trainServiceServices.findByHeadcode: Searching for headcode ${sanitizedHeadcode}`, 'dbug'); log.out('trainServiceServices.findByHeadcode: Searching for headcode ' +
sanitizedHeadcode, 'dbug');
const now = new Date(); const now = new Date();
const dayMap = ['su', 'm', 't', 'w', 'th', 'f', 's']; const dayMap = ['su', 'm', 't', 'w', 'th', 'f', 's'];
const shortDay = dayMap[now.getDay()]; // Fetch short day from map const shortDay = dayMap[now.getDay()]; // Fetch short day from map
@ -40,6 +41,8 @@ module.exports = {
/* Internal Functions, not to be exported */ /* Internal Functions, not to be exported */
/* Accepts the 'stops' array from a db query and produces an
array of only public stops as TIPLOCs. */
async function getPublicStops(data) { async function getPublicStops(data) {
let tiplocList = []; let tiplocList = [];
for (const publicStop in data) { for (const publicStop in data) {
@ -50,7 +53,10 @@ async function getPublicStops(data) {
return tiplocList; return tiplocList;
} }
async function parseTrains(data) { // Takes a single days data from a headcode query and returns only relevant services /* Takes a single days data from a headcode query and requeries
using the trainUid, required to ensure any cancellations are
accounted for */
async function parseTrains(data) {
let trainUids = []; let trainUids = [];
for (const i of data) { for (const i of data) {
const trainUid = i['trainUid']; const trainUid = i['trainUid'];
@ -66,7 +72,10 @@ async function parseTrains(data) { // Takes a single days data from a headcode q
return parsedData; return parsedData;
} }
async function findByTrainUid(uid, date = new Date()) { // Date defaults to today /* Queries using a trainUid and filters all schedules that
have been over-ridden by overlays, cancellations and new
schedules. */
async function findByTrainUid(uid, date = new Date()) {
const query = { const query = {
trainUid: uid, trainUid: uid,
scheduleStartDate: {$lte: date}, scheduleStartDate: {$lte: date},
@ -109,17 +118,21 @@ async function findByTrainUid(uid, date = new Date()) { // Date defaults to toda
if (stpIndicator === 'C') { if (stpIndicator === 'C') {
return; return;
//continue;
} }
if (stpIndicator === 'N' && !thisStpIndicators.hasC) { if (stpIndicator === 'N' &&
!thisStpIndicators.hasC) {
return serviceDetail; return serviceDetail;
//preparedData.push(serviceDetail);
} else if (stpIndicator === 'O' && !thisStpIndicators.hasC && !thisStpIndicators.hasN) { } else if (stpIndicator === 'O' &&
!thisStpIndicators.hasC &&
!thisStpIndicators.hasN) {
return serviceDetail; return serviceDetail;
//preparedData.push(serviceDetail);
} else if (stpIndicator === 'P' && !thisStpIndicators.hasC && !thisStpIndicators.hasN && !thisStpIndicators.hasO) { } else if (stpIndicator === 'P' &&
!thisStpIndicators.hasC &&
!thisStpIndicators.hasN &&
!thisStpIndicators.hasO) {
return serviceDetail; return serviceDetail;
//preparedData.push(serviceDetail);
} }
} }
return preparedData; return preparedData;

View File

@ -8,7 +8,8 @@ const minify = require('../utils/minify.utils');
async function isAuthed(uuid) { // Needs testing async function isAuthed(uuid) { // Needs testing
const q = {uuid: uuid}; const q = {uuid: uuid};
const res = await db.query('users', q); const res = await db.query('users', q);
log.out(`authUtils.checkUser: DB Query answer: ${JSON.stringify(res[0])}`, 'dbug'); log.out('authUtils.checkUser: DB Query answer: ' +
JSON.stringify(res[0]), 'dbug');
const authorized = res && res[0] && res[0].domain; const authorized = res && res[0] && res[0].domain;
if (authorized) db.userAtime(uuid); if (authorized) db.userAtime(uuid);
return authorized; return authorized;
@ -19,7 +20,8 @@ async function checkRequest(key) {
const collection = 'registrations'; const collection = 'registrations';
const query = {uuid: key}; const query = {uuid: key};
const res = await db.query(collection, query); const res = await db.query(collection, query);
log.out(`authUtils.checkRequest: DB Query result: ${JSON.stringify(res)}`, 'dbug'); log.out('authUtils.checkRequest: DB Query result: ' +
JSON.stringify(res), 'dbug');
const result = res.length > 0 && res[0].time const result = res.length > 0 && res[0].time
? { result: true, domain: res[0].domain } ? { result: true, domain: res[0].domain }
: { result: false }; : { result: false };
@ -44,7 +46,8 @@ async function generateConfirmationEmail(eml, uuid) {
html: htmlMin html: htmlMin
}; };
} catch(err) { } catch(err) {
log.out('mailServices.generateConfirmationEmail: Error reading templates, $(err)', 'err'); log.out('mailServices.generateConfirmationEmail: Error reading template, ' +
err, 'err');
return false; return false;
} }
} }

View File

@ -4,7 +4,6 @@ const san = require('../utils/sanitizer.utils'); // Sanitiser
async function checkCrs(input){ async function checkCrs(input){
var INPUT = input.toUpperCase(); var INPUT = input.toUpperCase();
log.out(`ldbUtils.checkCrs: Building database query to find: '${INPUT}'`, 'info');
var query = { var query = {
'$or':[ '$or':[
{'3ALPHA':INPUT}, {'3ALPHA':INPUT},
@ -13,11 +12,13 @@ async function checkCrs(input){
] ]
}; };
var result = await db.query('stations', query); var result = await db.query('stations', query);
log.out(`ldbUtils.checkCrs: Query results: ${JSON.stringify(result)}`, 'dbug'); log.out('ldbUtils.checkCrs: Query results: ' +
JSON.stringify(result), 'dbug');
return result; return result;
} }
async function cleanMessages(input){ // Needs to be moved to the frontend `ensureArray() func` // Needs to be moved to the frontend `ensureArray() func`
async function cleanMessages(input){
var out = []; var out = [];
if (typeof input.message == 'string') { if (typeof input.message == 'string') {
out.push(await san.cleanNrcc(input.message)); out.push(await san.cleanNrcc(input.message));
@ -30,7 +31,8 @@ async function cleanMessages(input){ // Needs to be moved to the frontend `ensur
} }
// Accepts an object but not an Array and returns it wrapped in an array. // Accepts an object but not an Array and returns it wrapped in an array.
async function cleanServices(input){ // Need to triple check but I don't think this is used anymore. // Need to triple check but I don't think this is used anymore.
async function cleanServices(input){
var out = []; var out = [];
if (!Array.isArray(input)) { if (!Array.isArray(input)) {
log.out(`ldbUtils.cleanServices: Transforming input: ${input}`, 'depr'); log.out(`ldbUtils.cleanServices: Transforming input: ${input}`, 'depr');

View File

@ -1,10 +1,10 @@
/* global process */
const environment = process.env.NODE_ENV; const environment = process.env.NODE_ENV;
const hideInProduction = ['info', 'dbug']; const hideInProduction = ['info', 'dbug'];
async function out(msg, level = 'othr') { async function out(msg, level = 'othr') {
if (environment === 'production' && hideInProduction.includes(level.toLowerCase())) { if (environment === 'production' &&
hideInProduction.includes(level.toLowerCase())) {
return; return;
} else { } else {
const time = new Date().toISOString(); const time = new Date().toISOString();

View File

@ -1,10 +1,10 @@
//const log = require('../utils/log.utils'); //const log = require('../utils/log.utils');
function removeNonAlphanumeric(inputString) { // Should be able to replace sanitizer module function removeNonAlphanumeric(inputString) {
return inputString.replace(/[^a-zA-Z0-9]/g, ''); return inputString.replace(/[^a-zA-Z0-9]/g, '');
} }
function removeNonAlpha(inputString) { // Should be able to replace sanitizer module function removeNonAlpha(inputString) {
return inputString.replace(/[^a-zA-Z]/g, ''); return inputString.replace(/[^a-zA-Z]/g, '');
} }