Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add linting #24

Merged
6 commits merged into from
Jul 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
env:
browser: true
commonjs: true
es6: true
jest: true
extends: standard
globals:
Atomics: readonly
SharedArrayBuffer: readonly
parserOptions:
ecmaVersion: 2018
rules: {
semi: [2, "always"],
space-before-function-paren: ["error", "never"]
}
14 changes: 7 additions & 7 deletions lib/errorHandler.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
const _handleUnconfiguredRoutes = (req, res) => {
console.warn(`Unconfigured route called: ${req.path}, method: ${req.method}`);
res.status(404);
res.json({
error: {
message: `Route ${req.path} and method ${req.method} are not configured.`,
},
})
console.warn(`Unconfigured route called: ${req.path}, method: ${req.method}`);
res.status(404);
res.json({
error: {
message: `Route ${req.path} and method ${req.method} are not configured.`
}
});
};

module.exports = _handleUnconfiguredRoutes;
10 changes: 5 additions & 5 deletions lib/metaData.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@ class MetaData {
this.responsesMetaData[path][method] = {};
}
this.responsesMetaData[path][method] = {
currentResIndex: 0,
currentResIndex: 0
};
}

nextResponseIndex(path, method, maxValue) {
const metaData = this.responsesMetaData[path][method];
if (!metaData) {
console.warn(`No meta data for ${method} to ${path}.`);
throw new Error("MetaData not initialized.");
throw new Error('MetaData not initialized.');
}
const currentValue = metaData.currentResIndex;
console.log(`calling callback for ${path} and ${method}`);
Expand All @@ -44,12 +44,12 @@ class MetaData {
return this.responsesMetaData.globalDelayMs;
}
const requestDelayMs = this.responsesMetaData[path][method].requestDelayMs;
return requestDelayMs ? requestDelayMs : this.responsesMetaData.globalDelayMs;
return requestDelayMs || this.responsesMetaData.globalDelayMs;
}
}

const isGlobalAccess = (path, method) => {
return !(path && method);
}
};

module.exports = MetaData;
module.exports = MetaData;
39 changes: 20 additions & 19 deletions mock-server.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
const express = require("express");
const _ = require("lodash");
const enableDestroy = require("server-destroy");
const morgan = require("morgan");
const express = require('express');
const _ = require('lodash');
const enableDestroy = require('server-destroy');
const morgan = require('morgan');
const unconfiguredRoutesHandler = require('./lib/errorHandler');
const MetaData = require('./lib/metaData');

const SUPPORTED_METHODS = ["get", "post", "put", "delete"];
const SUPPORTED_METHODS = ['get', 'post', 'put', 'delete'];
const isDebug = process.env.DEBUG || false;

class AietesServer {
Expand All @@ -26,7 +26,7 @@ class AietesServer {
return true;
});
} catch (e) {
log("Could not start Aietes server.");
log('Could not start Aietes server.');
if (isDebug) {
log(e);
}
Expand All @@ -40,7 +40,8 @@ class AietesServer {
}

reset(responses) {
log("Restarting Aietes server");
console.log('Restarting Aietes server');
log('Restarting Aietes server');
this._end();
this.responses = Object.assign({}, responses);
this.responsesMetaData.clear();
Expand All @@ -49,7 +50,7 @@ class AietesServer {
}

stop() {
log("Exiting Aietes server");
log('Exiting Aietes server');
this._end();
}

Expand All @@ -59,7 +60,7 @@ class AietesServer {

_setup() {
this.app = express();
this.app.use(morgan("tiny"));
this.app.use(morgan('tiny'));
this.app.locals = {
_: _
};
Expand Down Expand Up @@ -93,7 +94,7 @@ class AietesServer {
}

_createHandler(path, method) {
return async (req, res) => {
return async(req, res) => {
const endPointResponse = this.responses[path][method];
let currentResponse;
if (Array.isArray(endPointResponse)) {
Expand All @@ -104,30 +105,30 @@ class AietesServer {
}
const delayMs = this.responsesMetaData.getDelayMs(path, method);
return createSendResponseCallback(res, currentResponse, delayMs)();
}
};
}
}

const createSendResponseCallback = (handlerResponse, responseData, delayMs) => {
return async () => {
const returnStatus = responseData["status"] || 200;
return async() => {
const returnStatus = responseData['status'] || 200;
if (delayMs) {
log(`Delaying response for ${delayMs}ms`);
await setTimeout(() => {
handlerResponse
.status(returnStatus)
.set(responseData["headers"])
.jsonp(responseData["data"]);
.set(responseData['headers'])
.jsonp(responseData['data']);
}, delayMs);
} else {
log('Returning immediate response');
handlerResponse
.status(returnStatus)
.set(responseData["headers"])
.jsonp(responseData["data"]);
.set(responseData['headers'])
.jsonp(responseData['data']);
}
}
}
};
};

const log = data => {
if (!process.env.NO_OUTPUT) {
Expand Down
9 changes: 9 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
"test": "jest",
"test-dev": "jest --watchAll --verbose",
"coverage": "jest --coverage",
"eslint": "eslint .",
"coveralls": "jest --coverage && coveralls < ./coverage/lcov.info"
},
"pre-commit": "eslint",
"repository": "github:dtobe/aietes-js",
"author": "Tobias Ehrler <tobias_ehrler@yahoo.co.uk>",
"contributors": [
Expand All @@ -24,6 +26,13 @@
"server-destroy": "^1.0.1"
},
"devDependencies": {
"eslint": "^5.16.0",
"eslint-config-standard": "^12.0.0",
"eslint-plugin-import": "^2.17.2",
"eslint-plugin-node": "^8.0.1",
"eslint-plugin-promise": "^4.1.1",
"eslint-plugin-standard": "^4.0.0",
"pre-commit": "^1.2.2",
"coveralls": "^3.0.4",
"get-port": "^5.0.0",
"jest": "^24.8.0",
Expand Down
64 changes: 32 additions & 32 deletions samples/bitcoinPriceService.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,46 +3,46 @@ const express = require('express');
const router = express.Router();
const config = require('config');

router.get('/', async (req, res, next) => {
try {
const btcPrice = await getBitcoinPrice();
res.json({'btcPrice': btcPrice});
} catch (err) {
console.log("Some Error");
return next(err);
}
router.get('/', async(req, res, next) => {
try {
const btcPrice = await getBitcoinPrice();
res.json({ 'btcPrice': btcPrice });
} catch (err) {
console.log('Some Error');
return next(err);
}
});

router.get('/example', async (req, res, next) => {
try {
const btcPrice = await getBitcoinPrice();
router.get('/example', async(req, res, next) => {
try {
const btcPrice = await getBitcoinPrice();

if (btcPrice > 5000) {
res.json({
'btcPrice': {
"up": `${btcPrice}`
}
});
} else {
res.json({
'btcPrice': {
"down": `${btcPrice}`
}
});
if (btcPrice > 5000) {
res.json({
'btcPrice': {
'up': `${btcPrice}`
}
});
} else {
res.json({
'btcPrice': {
'down': `${btcPrice}`
}
} catch (err) {
console.log(`Some Error ${JSON.stringify(err)}`);
return next(err);
});
}
} catch (err) {
console.log(`Some Error ${JSON.stringify(err)}`);
return next(err);
}
});

const getBitcoinPrice = async () => {
const URL = config.get('end-point.external-service.currentprice');
const getBitcoinPrice = async() => {
const URL = config.get('end-point.external-service.currentprice');

const response = await axios.get(URL);
const data = await response.data.bpi.USD.rate_float;
const response = await axios.get(URL);
const data = await response.data.bpi.USD.rate_float;

return data;
return data;
};

module.exports = router;
module.exports = router;
115 changes: 57 additions & 58 deletions samples/integrationtest/bitcoin.sample-test.js
Original file line number Diff line number Diff line change
@@ -1,59 +1,58 @@
const request = require("supertest");
const getPort = require("get-port");
const MockServer = require("../../mock-server");
const testServerConfig = require("../test-setup/test-server-config");

const mockServerResponses = require("../test-setup/mock-data/price-above-5000");
const anotherMockServerResponse = require("../test-setup/mock-data/price-below-5000");

describe("Sample IT for the bitcoin service", () => {
let server;
let externalServiceMock;
let randomPort;

beforeAll(async () => {
randomPort = await getPort();
testServerConfig.setup({server_port: randomPort });
externalServiceMock = new MockServer(mockServerResponses, randomPort);
externalServiceMock.start();
});

beforeEach(() => {
server = require("../server");
});

afterEach(() => {
server.close();
});

afterAll(() => {
externalServiceMock.stop();
testServerConfig.clear();
});

const callExternalService = () => {
return request(server)
.get("/example")
};

it("should return 200 and display UP if Bitcoin price is above $5000", async () => {
const res = await callExternalService();
const responseMarkup = res.text;

expect(res.status).toBe(200);
expect(responseMarkup).toBeTruthy();
expect(responseMarkup).toContain("{\"btcPrice\":{\"up\":\"5148.82\"}}");
});

it("should return 200 and display DOWN if Bitcoin price is below $5000", async () => {
externalServiceMock.update(anotherMockServerResponse);

const res = await callExternalService();
const responseMarkup = res.text;

expect(res.status).toBe(200);
expect(responseMarkup).toBeTruthy();
expect(responseMarkup).toContain("{\"btcPrice\":{\"down\":\"4148.82\"}}");
});

const request = require('supertest');
const getPort = require('get-port');
const MockServer = require('../../mock-server');
const testServerConfig = require('../test-setup/test-server-config');

const mockServerResponses = require('../test-setup/mock-data/price-above-5000');
const anotherMockServerResponse = require('../test-setup/mock-data/price-below-5000');

describe('Sample IT for the bitcoin service', () => {
let server;
let externalServiceMock;
let randomPort;

beforeAll(async() => {
randomPort = await getPort();
testServerConfig.setup({ server_port: randomPort });
externalServiceMock = new MockServer(mockServerResponses, randomPort);
externalServiceMock.start();
});

beforeEach(() => {
server = require('../server');
});

afterEach(() => {
server.close();
});

afterAll(() => {
externalServiceMock.stop();
testServerConfig.clear();
});

const callExternalService = () => {
return request(server)
.get('/example');
};

it('should return 200 and display UP if Bitcoin price is above $5000', async() => {
const res = await callExternalService();
const responseMarkup = res.text;

expect(res.status).toBe(200);
expect(responseMarkup).toBeTruthy();
expect(responseMarkup).toContain('{"btcPrice":{"up":"5148.82"}}');
});

it('should return 200 and display DOWN if Bitcoin price is below $5000', async() => {
externalServiceMock.update(anotherMockServerResponse);

const res = await callExternalService();
const responseMarkup = res.text;

expect(res.status).toBe(200);
expect(responseMarkup).toBeTruthy();
expect(responseMarkup).toContain('{"btcPrice":{"down":"4148.82"}}');
});
});
Loading