Skip to content

Commit

Permalink
Refactor/bump node (#19)
Browse files Browse the repository at this point in the history
* Bump node 16

* var --> const and let

* Moved source files to lib folder

* Update package.json

Co-authored-by: Daniel Hillmann <[email protected]>

* Bump version 7.0.0

* Add CI workflow

---------

Co-authored-by: Daniel Hillmann <[email protected]>
  • Loading branch information
m-kusnierz and hilleer authored Dec 11, 2023
1 parent 156fa31 commit c768357
Show file tree
Hide file tree
Showing 25 changed files with 1,096 additions and 302 deletions.
46 changes: 46 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
name: Continuous integration (CI)

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

on:
pull_request:

jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 10

permissions:
id-token: write
contents: read
checks: write

steps:
- uses: actions/checkout@v3
- id: determine-node-npm-version
run: |
# tr-d '<=>' to trim '>=8.19.x' to '8.19.x' to prevent major version bumps (like [email protected] installed by npm i npm@>=8.19.x)
NODE_VERSION=$(jq -r '.engines.node' ./package.json | tr -d '<=>')
echo "node-version=${NODE_VERSION/null/16}" >> $GITHUB_OUTPUT
NPM_VERSION=$(jq -r '.engines.npm' ./package.json | tr -d '<=>')
echo "npm-version=${NPM_VERSION/null/}" >> $GITHUB_OUTPUT
NPM_POSTINSTALL=$(jq -r '.scripts.postinstall' ./package.json)
echo "npm-postinstall=${NPM_POSTINSTALL/null/}" >> $GITHUB_OUTPUT
- name: Use Node.js
uses: actions/setup-node@v3
with:
node-version: ${{ steps.determine-node-npm-version.outputs.node-version }}
cache: 'npm'
- name: Update NPM
if: steps.determine-node-npm-version.outputs.npm-version != ''
run: npm i npm@${{ steps.determine-node-npm-version.outputs.npm-version }} -g
- name: NPM CI
run: npm ci
- name: Lint
run: npm run lint --if-present
- name: ⚙️ Build
run: npm run build --if-present
- name: 🧪 NPM test
run: npm test
5 changes: 0 additions & 5 deletions .travis.yml

This file was deleted.

17 changes: 9 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Each schema will be loaded with `require`. This is an example of a schema in the

```js
//JSON Schemas defined according to the standard json-schema http://json-schema.org/latest/json-schema-core.html
var regexpPatternUtil = require("./util/regexpPatternUtil");
const regexpPatternUtil = require("./util/regexpPatternUtil");
module.exports = {
"description":"Login",
"required":true,
Expand All @@ -36,7 +36,7 @@ module.exports = {

When you require schemagic
```
var schemagic = require("schemagic");
const schemagic = require("schemagic");
```

You will find the following things on `schemagic.login`
Expand Down Expand Up @@ -188,9 +188,10 @@ like this:
```js
function getForeignKeyChecker(collectionName, propertyName) {
return function (documentIds, options, callback) {
var ids = [], formatErrors = [], anyFormatError = false;
const ids = [], formatErrors = [];
let anyFormatError = false;
documentIds.forEach(function (invoiceId) {
var id;
let id;
try {
id = new options.mongo.ObjectID(invoiceId);
formatErrors.push(true);
Expand All @@ -203,9 +204,9 @@ function getForeignKeyChecker(collectionName, propertyName) {
if(anyFormatError){
return callback(null, formatErrors);
}
var query = {};
const query = {};
query[propertyName] = {$in: ids};
var fields = {};
const fields = {};
fields[propertyName] = 1;
return options.mongo(collectionName).find(query, fields, getArray);

Expand All @@ -217,7 +218,7 @@ function getForeignKeyChecker(collectionName, propertyName) {
}

function checkResults(err, documentsInDb) {
var result;
let result;
if (err) {
return callback(err);
}
Expand All @@ -226,7 +227,7 @@ function getForeignKeyChecker(collectionName, propertyName) {
result = documentsInDb.map(Boolean); //truthy values become TRUE
return callback(null, result); //result array must have same order as array passed in documentIds param
}
var idsInDb = documentsInDb.map(function (invoice) {
const idsInDb = documentsInDb.map(function (invoice) {
return traverse(invoice).get(propertyName.split(".")).toString();
});
result = documentIds.map(function (id) {
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
var traverse = require('traverse');
var async = require('async');
const traverse = require('traverse');
const async = require('async');

module.exports = function foreignKeyValidationFactory(foreignKeys) {
return foreignKeyValidation;

function foreignKeyValidation(document, options, callback) {
var valuesToCheck = getValuesToCheck(foreignKeys, document);
const valuesToCheck = getValuesToCheck(foreignKeys, document);
if (Object.keys(valuesToCheck).length === 0) {
return callback(null, []);
}
var tasks = Object.keys(valuesToCheck).map(function (propertyName) {
var foreignKeyCheckFunction = foreignKeys[propertyName];
const tasks = Object.keys(valuesToCheck).map(function (propertyName) {
const foreignKeyCheckFunction = foreignKeys[propertyName];
return getForeignKeyCheckTask(foreignKeyCheckFunction, valuesToCheck[propertyName], options);
});
async.parallel(tasks, function (err, results) {
if (err) {
return callback(err);
}
var errors = Array.prototype.concat.apply([], results);
const errors = Array.prototype.concat.apply([], results);
return callback(null, errors);
});
}
};

function getValuesToCheck(foreignKeys, document) {
var memo = {};
let memo = {};
Object.keys(foreignKeys).forEach(function (propertyName) {
memo[propertyName] = [];
});
Expand All @@ -47,7 +47,7 @@ function getValuesToCheck(foreignKeys, document) {

function getForeignKeyCheckTask(foreignKeyCheckFunction, valuesToCheck, options) {
return function foreignKeyCheck(callback) {
var values = valuesToCheck.map(function (o) {
const values = valuesToCheck.map(function (o) {
return o.value;
});
return foreignKeyCheckFunction(values, options, returnErrors);
Expand All @@ -57,14 +57,14 @@ function getForeignKeyCheckTask(foreignKeyCheckFunction, valuesToCheck, options)
return callback(err);
}
if (validArray.length !== valuesToCheck.length) {
var error = new Error('Foreign key check function did not return array of same length as values array passed to it');
const error = new Error('Foreign key check function did not return array of same length as values array passed to it');
error.forignKeyFunction = foreignKeyCheckFunction.toString();
error.valuesPassed = values;
error.valuesReturned = validArray;
return callback(error);
}
var errors = [];
for (var i = 0; i < validArray.length; i++) {
const errors = [];
for (let i = 0; i < validArray.length; i++) {
if (!validArray[i]) {
errors.push({
property: valuesToCheck[i].path.join('.'),
Expand Down
30 changes: 15 additions & 15 deletions formats.js → lib/formats.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
var moment = require('moment');
var format = require('util').format;
var validUrl = require('valid-url');
const moment = require('moment');
const format = require('util').format;
const validUrl = require('valid-url');

module.exports = {
'date-time': datetimeFormatCheck,
Expand Down Expand Up @@ -37,10 +37,10 @@ function datetimeISOFormatCheck(value) {
datetimeFormatCheck.doc = format('Must be a date and time in the format %s', dateTimeFormat);
datetimeISOFormatCheck.doc = format('Must be a date and time in the iso format %s', isoDateTimeFormat);

var datePattern = /^\d{4}-\d{2}-\d{2}$/;
var dateFormat = 'YYYY-MM-DD';
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
const dateFormat = 'YYYY-MM-DD';
function dateFormatCheck(value) {
var dateTime = moment(value, dateFormat);
const dateTime = moment(value, dateFormat);
if (!dateTime || !dateTime.isValid() || !datePattern.test(value)) {
return false;
} else if (dateTime.year() < minYear) {
Expand All @@ -51,9 +51,9 @@ function dateFormatCheck(value) {
dateFormatCheck.doc = format('Must be a date in the format %s', dateFormat);


var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
var maxCurrency = MAX_SAFE_INTEGER / 100;
var minCurrency = -MAX_SAFE_INTEGER / 100;
const MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
const maxCurrency = MAX_SAFE_INTEGER / 100;
const minCurrency = -MAX_SAFE_INTEGER / 100;
function currencyFormatCheck(value) {
if (typeof value !== 'number') {
return true;
Expand All @@ -67,8 +67,8 @@ function currencyFormatCheck(value) {
currencyFormatCheck.doc = format('Must be a number with a maximum of two decimals after the decimal point. ' +
'Must be between %s and %s', minCurrency, maxCurrency);

var maxRate = 100;
var minRate = 0;
const maxRate = 100;
const minRate = 0;
function rateFormat(value) {
if (typeof value !== 'number') {
return true;
Expand All @@ -82,8 +82,8 @@ function rateFormat(value) {
rateFormat.doc = format('Must be a number with a maximum of two decimals after the decimal point. ' +
'Must be between %s and %s', minRate, maxRate);

var maxNegativeRate = 0;
var minNegativeRate = -100;
const maxNegativeRate = 0;
const minNegativeRate = -100;
function rateNegativeFormat(value) {
if (typeof value !== 'number') {
return true;
Expand All @@ -97,8 +97,8 @@ function rateNegativeFormat(value) {
rateNegativeFormat.doc = format('Must be a number with a maximum of two decimals after the decimal point. ' +
'Must be between %s and %s', minNegativeRate, maxNegativeRate);

var maxCurrencyRate = 999999999;
var minCurrencyRate = 0.000001;
const maxCurrencyRate = 999999999;
const minCurrencyRate = 0.000001;
function currencyRateFormat(value) {
if (typeof value !== 'number') {
return true;
Expand Down
48 changes: 24 additions & 24 deletions generateExampleJson.js → lib/generateExampleJson.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
//Generate example JSONs for schemas
//Examples are strings (so they can contain comments)
var wordWrap = require('word-wrap');
var formats = require('./formats');
var isProperty = require('is-property');
const wordWrap = require('word-wrap');
const formats = require('./formats');
const isProperty = require('is-property');

/*** BEGIN output class that encapsulated indentation ***/
var output = {
const output = {
addLine: function (line) {
if (this.value.length > 0) {
this.value += '\n'; //add linechange
}
this.addIndentedText(line);
},
indent: function () {
var array = [];
for (var i = 0; i < this.indentation; i++) {
const array = [];
for (let i = 0; i < this.indentation; i++) {
array.push(' ');
}
this.value += array.join('');
Expand All @@ -29,20 +29,20 @@ var output = {
};

function createOutput(indentation) {
var newOutput = Object.create(output);
const newOutput = Object.create(output);
newOutput.indentation = indentation;
newOutput.value = '';
return newOutput;
}
/*** END output class that encapsulated indentation ***/

function generateExampleJson(schema, minimal, noReadOnly, output) {
var type = schema.type;
let type = schema.type;
if (Array.isArray(type)) {
if (type.length === 0) {
throw new Error('type is array with length=0: ' + JSON.stringify(type));
}
for (var i = 0; i < type.length; i++) {
for (let i = 0; i < type.length; i++) {
if (type[i] !== 'null') {
type = type[i];
break; //exit for
Expand Down Expand Up @@ -86,9 +86,9 @@ function generateExampleJson(schema, minimal, noReadOnly, output) {
}

function getAllowsNull(schema) {
var type = schema.type;
const type = schema.type;
if (Array.isArray(type)) {
for (var i = 0; i < type.length; i++) {
for (let i = 0; i < type.length; i++) {
if (type[i] === 'null') {
return true;
}
Expand All @@ -98,12 +98,12 @@ function getAllowsNull(schema) {
}

function addIntro(schema, output) {
var allowNull = getAllowsNull(schema);
const allowNull = getAllowsNull(schema);
if (schema.description) {
var lines = wordWrap(schema.description, {width: 80, indent: '//'}).split('\n');
const lines = wordWrap(schema.description, {width: 80, indent: '//'}).split('\n');
lines.forEach(output.addLine.bind(output));
}
var doc;
let doc;
if (schema.readonly) {
output.addLine('//Read only. You do not need this on POST, PUT and PATCH. You can leave it in from what you GET, it will simply be ignored.');
} else {
Expand All @@ -130,8 +130,8 @@ function generateObjectJson(schema, minimal, noReadOnly, output) {
output.addText('{');
output.indentation++;

var comma = '';
for (var property in schema.properties) {
let comma = '';
for (let property in schema.properties) {
if (minimal && !schema.properties[property].required && !schema.properties[property].minimal) {
continue;
}
Expand All @@ -141,7 +141,7 @@ function generateObjectJson(schema, minimal, noReadOnly, output) {
if (schema.properties[property].hidden) {
continue;
}
var propertySchema = schema.properties[property];
const propertySchema = schema.properties[property];
output.addText(comma);
addIntro(propertySchema, output);
output.addLine(encodeProperty(property) + ':');
Expand Down Expand Up @@ -171,7 +171,7 @@ function generateArrayJson(schema, minimal, noReadOnly, output) {
output.addText('[');
output.indentation++;

var propertySchema = schema.items;
const propertySchema = schema.items;
addIntro(propertySchema, output);
output.addLine('');
generateExampleJson(propertySchema, minimal, noReadOnly, output);
Expand All @@ -182,18 +182,18 @@ function generateArrayJson(schema, minimal, noReadOnly, output) {
}

module.exports = function (schema, options) {
var asArray = options && options.asArray;
var minimal = options && options.minimal;
var noReadOnly = options && options.noReadOnly;
var output = createOutput(0);
const asArray = options && options.asArray;
const minimal = options && options.minimal;
const noReadOnly = options && options.noReadOnly;
const output = createOutput(0);
if (asArray) {
output.addLine('//Array');
output.addLine('[');
output.indentation++;
}
if (schema.description) {
var lines = wordWrap(schema.description, {width: 80, indent: '//'}).split('\n');
var lastLine = lines.pop();
const lines = wordWrap(schema.description, {width: 80, indent: '//'}).split('\n');
const lastLine = lines.pop();
lines.forEach(output.addLine.bind(output));
output.addLine(lastLine + '\n'); //we need linebreak because object (top level in schema) does not insert linebreak
output.indent();
Expand Down
Loading

0 comments on commit c768357

Please sign in to comment.