Skip to content

Commit

Permalink
Pass start dir to moduleconfig (#2)
Browse files Browse the repository at this point in the history
* export function instead of value returned from function call

* update package.json and bump node version

* update tests

* bump packages

* bump mocha

* require moduleconfig in function

* use parent-module

* use Debitoor fork of moduleconfig
  • Loading branch information
m-kusnierz authored Aug 17, 2023
1 parent 79ceee1 commit 946e0c3
Show file tree
Hide file tree
Showing 27 changed files with 3,672 additions and 1,344 deletions.
1 change: 1 addition & 0 deletions .jshintrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"esversion": 6,
"asi" : false,
"bitwise" : true,
"boss" : false,
Expand Down
5 changes: 5 additions & 0 deletions .mocharc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
require:
- ./test/common.js
ui: bdd
recursive: true
timeout: 4000
9 changes: 0 additions & 9 deletions .travis.yml

This file was deleted.

14 changes: 7 additions & 7 deletions readme.md → README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ module.exports = {

with the file above, you will be able to use your own errors like this:
```js
var errors = require("nodeerrors");
const errors = require("nodeerrors")();

callback(errors.notUnique("someProperty", "somePropertyValue")); //call callback with 'notUnique' error
```
Expand All @@ -49,7 +49,7 @@ Also these two parameters are automatically inserted into the error message wher

You will also be able to do like this:
```js
var errors = require("nodeerrors");
const errors = require("nodeerrors")();

callback(errors.propertyNotDefined("someProperty")); //call callback with 'propertyNotDefined' error
```
Expand All @@ -70,7 +70,7 @@ the property `http` and use it for a http status code in your response.
If you are passed an error in your own callback, you can parse it like this:

```js
var errors = require("nodeerrors");
const errors = require("nodeerrors")();

function (err, data){
if(err){
Expand Down Expand Up @@ -108,7 +108,7 @@ Adding extra internal values
You can always add an extra parameter, when you create an error. So if we take the ```propertyNotDefined``` example
from above, that took only one parameter, we can do this:
```js
var errors = require("nodeerrors");
const errors = require("nodeerrors")();

callback(errors.propertyNotDefined(
"someProperty",
Expand All @@ -118,7 +118,7 @@ callback(errors.propertyNotDefined(
This extra parameter will be added to the errors internal parameter. So when we parse the error:

```js
var errors = require("nodeerrors");
const errors = require("nodeerrors")();

function (err, data){
if(err){
Expand Down Expand Up @@ -149,8 +149,8 @@ one kind of error you return. When you do this, you can save the original error
object (```Error.prototype``` has been extended). So you can do something like this:

```js
var errors = require("nodeerrors");
var errorCodes = errors.errorCodes;
const errors = require("nodeerrors")();
const errorCodes = errors.errorCodes;

function handleDocument(err, document){
if(err){
Expand Down
10 changes: 5 additions & 5 deletions lib/middleware.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
"use strict";
'use strict';
module.exports = function(options){

var errors = require("nodeerrors");
const errors = require('nodeerrors');
return errorHandler;

function errorHandler(err, req, res, next){
var error = errors.parse(err);
const error = errors.parse(err);
req.error = JSON.parse(JSON.stringify(error)); //for logging of internal messages by logger
console.error(req.error);
if(!req.param("callback")){
if(!req.param('callback')){
res.statusCode = error.http; //only non-jsonp should get http status codes other than 200
delete error.http; //do not show http code to users (it's send in header)
}
delete error.internal; //do not show internal messages to users
res.json(error);
}
};
};
40 changes: 22 additions & 18 deletions lib/nodeerrors.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
"use strict";
var getErrorConfig = require("./util/getErrorConfig");
var makeErrorFunction = require("./util/makeErrorFunction");
var moduleConfig = require("moduleconfig");
var parse = require("./util/parse");
var middleware = require("./middleware");
'use strict';
const parentModule = require('parent-module');
const path = require('path');
const getErrorConfig = require('./util/getErrorConfig');
const moduleConfig = require('@debitoor/moduleconfig');
const makeErrorFunction = require('./util/makeErrorFunction');
const parse = require('./util/parse');
const middleware = require('./middleware');

function getNodeErrors() {
if (!moduleConfig.prototypesExtended) {
Expand All @@ -14,7 +16,7 @@ function getNodeErrors() {
return this;
};
Function.prototype.onError = function (callback) {
var fn = this;
const fn = this;
return function (err) {
if (err) {
err.callbackStack = err.callbackStack || new Error().stack;
Expand All @@ -29,27 +31,29 @@ function getNodeErrors() {
};
}

const startDir = path.dirname(parentModule());

return moduleConfig([".errors.js", "config/.errors.js"], function(errorConfigFilePath){
const loadPathFunction = (errorConfigFilePath) => {
//Not in cache, create nodeErrors object
var nodeError = {
errorCodes:{},
middleware:middleware
const nodeError = {
errorCodes: {},
middleware: middleware
};
nodeError.parse = parse.bind(nodeError);
var errorCodeSpecs = getErrorConfig(errorConfigFilePath);
var functionsToMake = Object.keys(errorCodeSpecs); //get array of friendly names.
for (var i = 0; i < functionsToMake.length; i++) {
//get error code friendly name, for example: "internalError"
var errorCodeName = functionsToMake[i];
const errorCodeSpecs = getErrorConfig(errorConfigFilePath);
const functionsToMake = Object.keys(errorCodeSpecs); //get array of friendly names.
for (let i = 0; i < functionsToMake.length; i++) {
//get error code friendly name, for example: 'internalError'
const errorCodeName = functionsToMake[i];
//make error function for friendly name
nodeError[errorCodeName] = makeErrorFunction(errorCodeName, errorCodeSpecs[errorCodeName]);
//save the error code in errorCodes
nodeError.errorCodes[errorCodeName] = errorCodeName;
}
return nodeError;
});
};

return moduleConfig({ startDir, paths: ['.errors.js', 'config/.errors.js'], loadPathFunction });
}

module.exports = getNodeErrors();
module.exports = getNodeErrors;
6 changes: 3 additions & 3 deletions lib/util/getErrorConfig.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"use strict";
'use strict';

function getErrorConfig(filePath) {
var config = JSON.parse(JSON.stringify(require(filePath))); //make copy so we do not alter original
const config = JSON.parse(JSON.stringify(require(filePath))); //make copy so we do not alter original
if (!config.system) {
config.system = {
message:"There was an internal server error",
message:'There was an internal server error',
http:500
};
}
Expand Down
20 changes: 10 additions & 10 deletions lib/util/getSerializableError.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
"use strict";
var util = require("util");
'use strict';
const util = require('util');
module.exports = function getSerializableError(err) {
//this copying of properties is needed to get Error properties serialized by JSON.stringify
var output = {};
const output = {};
//In order to get stack trace and so on, we use Object.getOwnPropertyNames, to get non-enumerable properties
err && (typeof err === 'object') && Object.getOwnPropertyNames(err).forEach(function (property) {
if (err[property] !== undefined && property !== "nodeErrors") {
if (property === "innerError" || property === "internal") {
if (err[property] !== undefined && property !== 'nodeErrors') {
if (property === 'innerError' || property === 'internal') {
output[property] = getSerializableError(err[property]); //deep copy, even if it has cyclic references.
} else {
if (shouldSerialize(err[property])) {
output[property] = err[property];
} else {
output[property] = "[cyclic or too complex]";
output[property] = '[cyclic or too complex]';
}
}
}
Expand All @@ -21,7 +21,7 @@ module.exports = function getSerializableError(err) {
};

function shouldSerialize(obj) {
var count = 0;
let count = 0;
return _shouldSerialize(obj);

function _shouldSerialize(obj) {
Expand All @@ -34,15 +34,15 @@ function shouldSerialize(obj) {
return true;
}
if (util.isArray(obj)) {
for (var j = 0; j < obj.length; j++) {
for (let j = 0; j < obj.length; j++) {
if (!_shouldSerialize(obj[j])) {
return false;
}
}
}
//JSON.stringify stringifies enumerable properties, so we use Object.keys
var keys = Object.keys(obj), len = keys.length;
for (var i = 0; i < len; i++) {
const keys = Object.keys(obj), len = keys.length;
for (let i = 0; i < len; i++) {
if (!_shouldSerialize(obj[keys[i]])) {
return false;
}
Expand Down
29 changes: 15 additions & 14 deletions lib/util/makeErrorFunction.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
"use strict";
var format = require("util").format;
var uuid = require("uuid");
'use strict';
const format = require('util').format;
const uuid = require('uuid');

module.exports = function makeErrorFunction(errorCodeName, errorCodeSpec) {
if (!errorCodeName) {
throw new Error("The error code specification has no name");
throw new Error('The error code specification has no name');
}

return function () {
var error = new Error(""), message;
error.id = "myId";
const error = new Error('');
let message;
error.id = 'myId';
error.code = errorCodeName;
//get error message
if (errorCodeSpec.args) {
var numberOfFormatArguments = (errorCodeSpec.message.match(/\%s|\%d|\%j/g) || []).length;
var formatArguments = [errorCodeSpec.message];
var nonInternalArguments = Array.prototype.slice.call(arguments, 0, numberOfFormatArguments);
const numberOfFormatArguments = (errorCodeSpec.message.match(/\%s|\%d|\%j/g) || []).length;
const formatArguments = [errorCodeSpec.message];
const nonInternalArguments = Array.prototype.slice.call(arguments, 0, numberOfFormatArguments);
formatArguments.push.apply(formatArguments, nonInternalArguments);
message = format.apply(format, formatArguments);
} else {
Expand All @@ -24,10 +25,10 @@ module.exports = function makeErrorFunction(errorCodeName, errorCodeSpec) {
error.message = message;
error.id = uuid.v4();
//add arguments
var i = 0;
let i = 0;
if (errorCodeSpec.args) {
for (i = 0; i < errorCodeSpec.args.length; i++) {
var argName = errorCodeSpec.args[i];
const argName = errorCodeSpec.args[i];
if (arguments[i]) {
error[argName] = arguments[i];
}
Expand All @@ -39,10 +40,10 @@ module.exports = function makeErrorFunction(errorCodeName, errorCodeSpec) {
error.internal = error.internal || {};
error.internal.nodeErrors = true;
//add additional error code spec properties
var properties = Object.keys(errorCodeSpec);
const properties = Object.keys(errorCodeSpec);
for(i=0; i<properties.length; i++){
var propertyName = properties[i];
if(propertyName !== "args" && propertyName !== "message"){
const propertyName = properties[i];
if(propertyName !== 'args' && propertyName !== 'message'){
error[propertyName] = errorCodeSpec[propertyName];
}
}
Expand Down
10 changes: 5 additions & 5 deletions lib/util/parse.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"use strict";
var uuid = require("uuid");
var getSerializableError = require("./getSerializableError");
'use strict';
const uuid = require('uuid');
const getSerializableError = require('./getSerializableError');

module.exports = function parseError(err) {
var errors = this;
var error;
const errors = this;
let error;
if(err && err.internal && err.internal.nodeErrors){
error = getSerializableError(err);
} else {
Expand Down
Loading

0 comments on commit 946e0c3

Please sign in to comment.