Skip to content

Commit

Permalink
updated dependencies, removed Babel and related files, improved comme…
Browse files Browse the repository at this point in the history
…nts of API response validation against OpenAPI schema, added example of HTTP server mock with axios client
  • Loading branch information
francescozanoni committed Dec 25, 2020
1 parent 302a0da commit ba241e2
Show file tree
Hide file tree
Showing 11 changed files with 94 additions and 216 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ node_modules/
.idea/
yarn.lock
package-lock.json
.npm/
10 changes: 1 addition & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ Several basic examples and experiments with JavaScript.
* `src/tree.html`: tree rendering example with [Treant.js](http://fperucic.github.io/treant-js) package
* `src/streams`: examples with Node's [streams](https://nodejs.org/api/stream.html)
* `.eslintrc.json`: configuration for [ESLint](https://eslint.org) package
* `babel.config.json`: configuration file for [Babel](https://babeljs.io), customized for [React JS](https://reactjs.org) and very old browsers on Apple [iOS](https://www.apple.com/ios) 9.3


### Test examples
Expand All @@ -27,7 +26,7 @@ Several basic examples and experiments with JavaScript.
* `tests/error-within-async.test.js`: ensure unexpected errors raised within asynchronous code do not jeopardize tests performed by [Jest](https://jestjs.io) framework
* `tests/fastify.test.js`: test [Fastify](https://www.fastify.io)-based web application
* `tests/fs-mock.test.js`: mock external module functions with [Jest](https://jestjs.io) framework
* `tests/openapi-validator.test.js`: validate API response against OpenAPI schema
* `tests/openapi-validator.test.js`: validate API response against [OpenAPI](https://swagger.io/specification) schema with [jest-openapi](https://github.com/openapi-library/OpenAPIValidators/tree/master/packages/jest-openapi) package


### Experiments
Expand All @@ -53,18 +52,11 @@ Several basic examples and experiments with JavaScript.
docker run -v ${PWD}:/code -w /code --rm node:alpine yarn lint


### Code transpilation

docker run -v ${PWD}:/root -w /root --rm node:alpine npx babel /root/src/react/script.js -o /root/src/react/script.transpiled.js



----


### Notes

* in order to avoid warning `TypeError: this.cliEngine is not a constructor` within IDE, I've switched to [ESLint](https://eslint.org) 5, as suggested [here](https://intellij-support.jetbrains.com/hc/en-us/community/posts/360004195120-TypeError-this-cliEngine-is-not-a-constructor)
* test files are suffixed by `.test.js`, in order to comply with [Jest](https://jestjs.io) default, so no further parameter is required
* in order to avoid warning `Unresolved function/method/variable` within IDE, I've added `@types/jest` package, as suggested [here](https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000357324-Get-rid-of-Unresolved-function-method-variable-warning-in-Jest-test-files)
* (this could seem advertising, I know) a **LOT** of examples can be found on book [JavaScript: The Definitive Guide (7th ed.)](https://www.oreilly.com/library/view/javascript-the-definitive/9781491952016), by [David Flanagan](https://davidflanagan.com)
11 changes: 0 additions & 11 deletions babel.config.json

This file was deleted.

14 changes: 4 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,29 +9,23 @@
"author": "Francesco Zanoni <francescozanoni81@gmail.com>",
"license": "MIT",
"dependencies": {
"ajv": "^6.12.6",
"ajv": "^7.0.2",
"axios": "^0.21.1",
"fastify": "^3.6.0",
"lodash": "^4.17.20",
"node-fetch": "^2.6.0"
},
"devDependencies": {
"@babel/cli": "^7.12.1",
"@babel/core": "^7.12.3",
"@babel/preset-env": "^7.12.1",
"@babel/preset-react": "^7.12.5",
"@types/jest": "^26.0.15",
"eslint": "^5",
"eslint-config-standard": "^14.1.1",
"eslint": "^7.16.0",
"eslint-config-standard": "^16.0.2",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-react": "^7.21.5",
"eslint-plugin-standard": "^4.0.1",
"jest": "^26.5.3",
"jest-openapi": "^0.11.0",
"nock": "^13.0.4",
"regenerator-runtime": "^0.13.7"
"nock": "^13.0.4"
},
"scripts": {
"test": "jest",
Expand Down
34 changes: 17 additions & 17 deletions src/aiken-validator/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@
* ]
*/
function validateOne (question) {
var result = []
var questionNumberSeparator = ''
var questionNumbers = []
var questionLines = question.split('\n')
const result = []
let questionNumberSeparator = ''
const questionNumbers = []
const questionLines = question.split('\n')

// Result structure is prepared.
for (var i = 0; i < questionLines.length; i++) {
var o = {}
for (let i = 0; i < questionLines.length; i++) {
const o = {}
o[questionLines[i]] = false
result.push(o)
}
Expand All @@ -40,10 +40,10 @@ function validateOne (question) {
}

// Question answers validation.
for (var j = 1; j < questionLines.length - 1; j++) {
var answer = questionLines[j]
var answerNumber = answer.substr(0, 1)
var answerNumberSeparator = answer.substr(1, 1)
for (let j = 1; j < questionLines.length - 1; j++) {
const answer = questionLines[j]
const answerNumber = answer.substr(0, 1)
const answerNumberSeparator = answer.substr(1, 1)
// Answer generic validation.
if (/^[A-Z](.|\)) .+/.test(answer) === true) {
result[j][answer] = true
Expand Down Expand Up @@ -83,18 +83,18 @@ function validateOne (question) {
* @param {HTMLDivElement} outputElement - HTML element reporting questions validity
*/
function validateAll (inputElement, outputElement) {
var questions = inputElement.value.trim().replace(/\r?\n/g, '\n').split('\n\n')
const questions = inputElement.value.trim().replace(/\r?\n/g, '\n').split('\n\n')

for (var question of questions) {
var questionValidity = validateOne(question)
for (const question of questions) {
const questionValidity = validateOne(question)

var isQuestionValid = questionValidity.every(function (item) {
const isQuestionValid = questionValidity.every(function (item) {
return Object.values(item)[0] === true
})

for (var lineValidity of questionValidity) {
var line = Object.entries(lineValidity)[0][0]
var isLineValid = Object.entries(lineValidity)[0][1]
for (const lineValidity of questionValidity) {
const line = Object.entries(lineValidity)[0][0]
const isLineValid = Object.entries(lineValidity)[0][1]

if (isQuestionValid === true) {
outputElement.innerHTML += renderLineOfValidQuestion(line)
Expand Down
18 changes: 0 additions & 18 deletions src/react/index.transpiled.html

This file was deleted.

96 changes: 0 additions & 96 deletions src/react/script.transpiled.js

This file was deleted.

19 changes: 9 additions & 10 deletions src/streams/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,21 @@
// - http://codewinds.com/blog/2013-08-20-nodejs-transform-streams.html
// - https://nodejs.org/api/stream.html#stream_class_stream_transform

const fs = require('fs');
const Utils = require('src/utils');
const UpperCaseTransform = require('UpperCaseTransform');
const fs = require('fs')
const Utils = require('src/utils')
const UpperCaseTransform = require('UpperCaseTransform')

// ---------------------------------------------------------------------------------------------

console.log(Utils.getDateTime());
console.log(Utils.getDateTime())

const readStream = fs.createReadStream('/path/to/input_file.txt');
const writeStream = fs.createWriteStream('/path/to/output_file.txt');
const upperCaseTransform = new UpperCaseTransform();
const readStream = fs.createReadStream('/path/to/input_file.txt')
const writeStream = fs.createWriteStream('/path/to/output_file.txt')
const upperCaseTransform = new UpperCaseTransform()

readStream
.pipe(upperCaseTransform)
.pipe(writeStream)
.on('finish', function () {
console.log(Utils.getDateTime());
});

console.log(Utils.getDateTime())
})
16 changes: 8 additions & 8 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,17 @@ function onlyUnique (item, index, array) {
* @see https://usefulangle.com/post/187/nodejs-get-date-time
*/
function getDateTime () {
const date_ob = new Date()
const date = ('0' + date_ob.getDate()).slice(-2)
const month = ('0' + (date_ob.getMonth() + 1)).slice(-2)
const year = date_ob.getFullYear()
const hours = ('0' + date_ob.getHours()).slice(-2)
const minutes = ('0' + date_ob.getMinutes()).slice(-2)
const seconds = ('0' + date_ob.getSeconds()).slice(-2)
const dateObject = new Date()
const date = ('0' + dateObject.getDate()).slice(-2)
const month = ('0' + (dateObject.getMonth() + 1)).slice(-2)
const year = dateObject.getFullYear()
const hours = ('0' + dateObject.getHours()).slice(-2)
const minutes = ('0' + dateObject.getMinutes()).slice(-2)
const seconds = ('0' + dateObject.getSeconds()).slice(-2)
return year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds
}

module.exports = {
onlyUnique,
getDateTime
}
}
39 changes: 30 additions & 9 deletions tests/http-server-mock.test.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,37 @@
const fetch = require('node-fetch')
const axios = require('axios')
const nock = require('nock')

test('Mock HTTP server', async () => {
// This is required to make nock correctly intercept axios requests.
// https://github.com/axios/axios/issues/305
axios.defaults.adapter = require('axios/lib/adapters/http')

describe('Mock HTTP server', () => {
test('node-fetch client', async () => {
// Mock HTTP server
nock('http://hostname')
.get('/path')
.reply(200, 'text to return')

// Request to HTTP server
const response = await fetch('http://hostname/path')

const body = await response.text()

expect(response.status).toBe(200)
expect(body).toBe('text to return')
})

test('axios client', async () => {
// Mock HTTP server
nock('http://hostname')
.get('/path')
.reply(200, 'text to return')
nock('http://hostname')
.get('/path')
.reply(200, 'text to return')

// Request to HTTP server
const response = await fetch('http://hostname/path')
const body = await response.text()
// Request to HTTP server
const response = await axios.get('http://hostname/path')

expect(response.status).toBe(200)
expect(body).toBe('text to return')
expect(response.status).toBe(200)
expect(response.data).toBe('text to return')
})
})

0 comments on commit ba241e2

Please sign in to comment.