Skip to content

Commit

Permalink
lib: refactor record-serialization.js
Browse files Browse the repository at this point in the history
Get rid of nested try-catch statements. Decouple `safeRequire` function
that can be used later.

PR-URL: #41
  • Loading branch information
aqrln committed Jan 31, 2017
1 parent d2459a8 commit 2e2c8cc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 16 deletions.
11 changes: 11 additions & 0 deletions lib/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,14 @@ common.forwardMultipleEvents = (from, to, eventNames) => {
common.forwardEvent(from, to, event);
});
};

// Try to require `moduleName` and return the exported object if the module is
// found or null otherwise.
//
common.safeRequire = (moduleName) => {
try {
return require(moduleName);
} catch (err) {
return null;
}
};
27 changes: 11 additions & 16 deletions lib/record-serialization.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use strict';

const safeRequire = require('./common').safeRequire;
const serializerFactory = require('./serializer-factory');

const jsrs = {};
Expand All @@ -11,26 +12,20 @@ module.exports = jsrs;
// one of our priorities to optimize it.
const USE_NATIVE_SERIALIZER = false;

let jstpNative;

try {
jstpNative = require('../build/Release/jstp');
} catch (e) {
try {
jstpNative = require('../build/Debug/jstp');
} catch (e) {
console.warn(
'JSTP native addon is not built. ' +
'Run `npm install` in order to build it, otherwise you will get ' +
'poor server performance under load.'
);
module.exports = require('./record-serialization-fallback');
}
}
const jstpNative =
safeRequire('../build/Release/jstp') ||
safeRequire('../build/Debug/jstp');

if (jstpNative) {
Object.assign(jsrs, jstpNative);
if (!USE_NATIVE_SERIALIZER) {
jsrs.stringify = serializerFactory.createSerializer();
}
} else {
console.warn(
'JSTP native addon is not built. ' +
'Run `npm install` in order to build it, otherwise you will get ' +
'poor server performance under load.'
);
module.exports = require('./record-serialization-fallback');
}

0 comments on commit 2e2c8cc

Please sign in to comment.