Skip to content

Commit

Permalink
Merge pull request #16 from secanis/expand-tests
Browse files Browse the repository at this point in the history
test: improve tests and fix bugs
  • Loading branch information
matthiasbaldi authored Nov 17, 2018
2 parents 8af3eab + cabfc4e commit bbe18c9
Show file tree
Hide file tree
Showing 16 changed files with 571 additions and 163 deletions.
2 changes: 1 addition & 1 deletion server/api/routes_auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ module.exports = (router) => {
} else {
req.decoded = decoded;
res.send({
message: 'your token is vaild.', status: 'inf'
message: 'your token is vaild.', status: 'info'
});
}
});
Expand Down
4 changes: 4 additions & 0 deletions server/api/routes_settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,10 @@ module.exports = (router) => {
securityTokenHash.update(new Date().getTime().toString());
process.env.STJORNACONFIG_PASSWORD_SECRECT = securityTokenHash.digest('hex');
req.body.config.installed = true;

// check if data folder exists, if not create it
fileHelper.createFolder(process.env.STJORNA_SERVER_STORAGE);

// create initial config file
fileHelper.saveConfigFile(req.body.config, (err, config) => {
if (err) {
Expand Down
1 change: 1 addition & 0 deletions server/lib/env_default.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ module.exports = {
process.env['STJORNA_SERVER_PORT'] = process.env.STJORNA_SERVER_PORT || 3000;
process.env['STJORNA_SERVER_MAX_UPLOAD'] = process.env.STJORNA_SERVER_MAX_UPLOAD || '5mb';
process.env['STJORNA_LOGLEVEL'] = process.env.STJORNA_LOGLEVEL || 'info';
process.env['STJORNA_REQUEST_LOG'] = process.env.STJORNA_REQUEST_LOG || '';
process.env['STJORNA_CRON_CLEANUP_INTERVAL'] = process.env.STJORNA_CRON_CLEANUP_INTERVAL || '00 3 * * *';
process.env['STJORNA_SERVER_STORAGE'] = process.env.STJORNA_SERVER_STORAGE || `${process.cwd()}/data`;

Expand Down
4 changes: 1 addition & 3 deletions server/lib/export/excel.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
const path = require('path');
const fs = require('fs');
var xl = require('excel4node');
const xl = require('excel4node');

const dbHelper = require('../database_helper.js');

Expand Down
7 changes: 6 additions & 1 deletion server/lib/file_helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const exportJson = require('./export/json.js');

module.exports = {
getFolderContent: (route, cb) => {
// build a complete file tree of all things within a route, base route is /data/uploads/<username>
// build a complete file tree of all things within a route, base route is /<data>/uploads/<username>
let files = fs.readdir(route, 'utf8', (err, files) => {
let fileList = [];
if (files) {
Expand Down Expand Up @@ -55,6 +55,11 @@ module.exports = {
}
});
},
createFolder: (dir) => {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
},
loadConfigFile: (cb) => {
// load config file and call the cb
fs.readFile(`${process.env.STJORNA_SERVER_STORAGE}/config.json`, 'utf8', cb);
Expand Down
4 changes: 2 additions & 2 deletions server/lib/image_helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ module.exports = {
let buff = Buffer.from(data, 'base64');
// generate new hash for imagename
let hash = crypto.createHash('sha1').update(`${data}-${new Date().getTime()}`, 'utf8').digest('hex');
let imagePath = `/data/uploads/${userid}${additionalPath}/${hash}.jpeg`;
let imagePath = `/uploads/${userid}${additionalPath}/${hash}.jpeg`;
fileHelper.loadConfigFile((err, config) => {
if (!err) {
config = JSON.parse(config);
// resize and set the quality for the image and save it
Jimp.read(buff).then((image) => {
image.resize(config.image_dimension, config.image_dimension)
.quality(config.image_quality)
.write(`${__dirname}/..${imagePath}`, (err) => {
.write(`${process.env.STJORNA_SERVER_STORAGE}/${imagePath}`, (err) => {
if (err) {
logger.error(`image - error occured while writing image to filesystem: ${err.message}`);
}
Expand Down
116 changes: 74 additions & 42 deletions server/lib/logging_helper.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,33 @@
const winston = require('winston');
const expressWinston = require('express-winston');

// build pattern for stjorna log format
const buildStjornaLogFormat = (info) => {
const padding = info.level.length <= 7 ? 7 : 17;
// detect component, if not write nothing
let component = info.message.replace(/\s\-\s.*$/g, '');
if (component !== info.message) {
info.message = info.message.replace(`${component} - `, '');
component = `[${component}] `;
} else {
component = '';
}
return `${info.timestamp} [${info.label}] [${info.level.padEnd(padding, '')}] ${component}${info.message}`;
};

// build pattern for stjorna request log format
const buildStjornaRequestLogFormat = (req) => {
return `${req.timestamp} [${req.label}] ${req.message}`;
};

// set logging format for application logs
const stjornaLogFormat = winston.format.combine(
winston.format.colorize({
all: true
}),
winston.format.label({ label: 'stjorna' }),
winston.format.timestamp(),
winston.format.printf((info) => {
const padding = info.level.length <= 7 ? 7 : 17;
// detect component, if not write nothing
let component = info.message.replace(/\s\-\s.*$/g, '');
if (component !== info.message) {
info.message = info.message.replace(`${component} - `, '');
component = `[${component}] `;
} else {
component = '';
}
return `${info.timestamp} [${info.label}] [${info.level.padEnd(padding, '')}] ${component}${info.message}`;
})
winston.format.printf(buildStjornaLogFormat)
);

// set logging format for request logs
Expand All @@ -29,37 +37,61 @@ const stjornaRequestLogFormat = winston.format.combine(
}),
winston.format.label({ label: 'stjorna-req' }),
winston.format.timestamp(),
winston.format.printf((req) => {
return `${req.timestamp} [${req.label}] ${req.message}`;
})
winston.format.printf(buildStjornaRequestLogFormat)
);

const isSlientLogActivated = (logType) => {
switch (logType) {
case 'application':
if (process.env.STJORNA_LOGLEVEL === 'slient') {
return true;
}
break;
case 'request':
if (process.env.STJORNA_REQUEST_LOG === 'slient') {
return true;
}
break;
}
return false;
};

// classic logger configuration (console.log stuff)
const logger = winston.createLogger({
level: process.env.STJORNA_LOGLEVEL,
transports: [
new (winston.transports.Console)({
format: winston.format.combine(winston.format.colorize(), stjornaLogFormat),
silent: isSlientLogActivated('application')
})
// new winston.transports.File({ filename: 'combined.log' })
]
});

// express logger configuration
const configureExpressLogging = expressWinston.logger({
transports: [
new winston.transports.Console({
format: winston.format.combine(winston.format.colorize(), stjornaRequestLogFormat)
})
],
level: (req, res) => {
let level = '';
if (res.statusCode >= 100) { level = 'info'; }
if (res.statusCode >= 400) { level = 'warn'; }
if (res.statusCode >= 500) { level = 'error'; }
return level;
},
statusLevels: false,
expressFormat: true,
colorize: true,
ignoreRoute: (req, res) => { return isSlientLogActivated('request'); }
});

module.exports = {
// classic logger configuration (console.log stuff)
logger: winston.createLogger({
level: process.env.STJORNA_LOGLEVEL,
transports: [
new (winston.transports.Console)({
format: winston.format.combine(winston.format.colorize(), stjornaLogFormat)
})
// new winston.transports.File({ filename: 'combined.log' })
]
}),
// express logger configuration
configureExpressLogging: expressWinston.logger({
transports: [
new winston.transports.Console({
format: winston.format.combine(winston.format.colorize(), stjornaRequestLogFormat)
})
],
level: (req, res) => {
let level = '';
if (res.statusCode >= 100) { level = 'info'; }
if (res.statusCode >= 400) { level = 'warn'; }
if (res.statusCode >= 500) { level = 'error'; }
return level;
},
statusLevels: false,
expressFormat: true
})
logger,
configureExpressLogging,
_buildStjornaLogFormat: buildStjornaLogFormat,
_buildStjornaRequestLogFormat: buildStjornaRequestLogFormat,
_isSlientLogActivated: isSlientLogActivated
};
6 changes: 3 additions & 3 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
"start": "nodemon --ignore data/ server.js",
"apidoc:private": "apidoc --private true -i ./api -o ./apidoc-private/",
"apidoc:public": "apidoc --private false -i ./api -o ./apidoc/",
"test": "rimraf data & rimraf reports & npm run test:coverage",
"test:coverage": "nyc --reporter html --reporter lcovonly --report-dir reports/coverage --temp-directory reports/coverage/.nyc_output --reporter text npm run test:api",
"test:api": "mocha --reporter mocha-multi-reporters --reporter-options configFile=test/_config.json --timeout 5000 --full-trace --exit",
"test": "rimraf test/testdata & rimraf reports & npm run test:coverage",
"test:coverage": "nyc --reporter html --reporter lcovonly --report-dir reports/coverage --temp-dir reports/coverage/.nyc_output --reporter text npm run test:api",
"test:api": "mocha test/**/*.spec.js --reporter mocha-multi-reporters --reporter-options configFile=test/_config.json --timeout 5000 --full-trace --exit",
"test:sendcoverage": "cat reports/coverage/lcov.info | codacy-coverage"
},
"author": "[email protected]",
Expand Down
Loading

0 comments on commit bbe18c9

Please sign in to comment.