razorUX JS Utils
My collection of custom Node.js utilities.
Small useful, and constantly improved!
- Working with environment variables
- Read/write files: plaintext, CSV, and JSON
- Normalize tokens
- Dollar /cents conversion
- Functional
pipe
methods - Object cloning
- Iteration syntax sugar
- Sleep
- Enable / disable console
- Base64 encode/decode
- Insecure random numbers
- Retry network errors
- Type Assertions
- Slack messaging
- JSON caching with Memcachier
Installation
npm install razorux-js-utils
Included functions
loadEnvVars(filePath);
validateEnvVars([ ENV_VAR ]);
readCsvFile(path);
writeCsvFile(data, path);
readTextFile(path);
ensureDirExists(path);
readJsonFile(path);
writeJsonFile(data, path);
normalizeToken(string);
dollarsToCents(number);
centsToDollars(number);
invokeMethod(Function);
pipe([ function() {}, function() {} ]);
map([], function() {});
reduce([], function() {});
objectToEntries({});
entriesToObject([key, value]);
clone(Object)
asyncMap(Array, Function);
asyncForEach(Array, Function);
sendSlackNotification,
getCloudWatchLogDeeplink()
sendErrorNotification,
simpleHash(Any)
sleep(number)
parseBoolean(String);
retryable({fn, retryCount = 3, timeout = 300, addRandomDelay = true});
validateJson(json, requiredPaths);
createErrorType(name, suppressErrorNotification);
enableConsoleLogging();
disableConsoleLogging();
base64ToString,
stringToBase64
Modules
Insecure Random
const n = randomNumberBetween(0, 42);
# => a random number within range, **inclusive**
Base64
A pair of functions to encode/decode base64 strings.
Works exactly as you'd expect.
const b64 = stringToBase64("Just you wait, Henry Higgins, just you wait...")
base64ToString(b64)
Retry
This package includes a powerful retry function for retrying pretty much any function, including async promises.
const {
retry
} = require('main');
function myAsyncFunction() { ... }
await retry(myAsyncFunction);
const ONE_SECOND = 1000;
const ONE_MINUTE = 1000 * 60;
await retry(myAsyncFunction, {
backoff: true,
jitter: true,
minRetryDelay: ONE_SECOND,
maxRetryDelay: 3 * ONE_MINUTE,
timeout: 10 * ONE_MINUTE,
});
await retry(
myAsyncFunction,
{
onError = ()=>{
},
maxRetryCount: Number.MAX_SAFE_INTEGER
timeout: 1000,
retryDelayMs: 50,
backoff: false,
factor: 2,
minRetryDelay: 0,
maxRetryDelay: 1000 * 60 * 2,
jitter: false,
minJitterMs: 0,
maxJitterMs: 50,
debugLogging: false
})
Caching with Memcachier
Dead-easy temporary JSON storage in Memcache.
You'll need to sign up for a free Memcachier account here.
First, make sure you've set the following environment variables:
MEMCACHIER_SERVER,
MEMCACHIER_USERNAME
MEMCACHIER_PASSWORD
CACHE_EXPIRATION_TIMEOUT_SECONDS = 60 * 60; // 1 hour
MEMCACHE_LOGGING_ENABLED=true
Usage:
const data = { text: "Hello World!", passenger: "Mr. Frumble" }
const key = "top_secret_key"
const cache = createCacheClient();
const storageResponse = await cache.persist(key, data);
const retrieveResponse = await cache.retrieve(key);
JSON is automatically serialized and deserialized
Type Assertions
A collection of type assertions, if you need them.
assert*
functions throw an error if the value doesn't match. A match returns nothing. (The default error is TypeError
. A custom error class can be used instead. )is*
functions return true
or false
.
You can optionally customize the name of the error in the error message, and the error message class.
const arg = 42;
assertTypeString(arg);
assertTypeString(arg, 'Input String', MyInputStringError);
Included assertions:
assertDefined(arg, argName, customErrorClass);
assertTruthy(arg, argName, customErrorClass);
assertTypeString(arg, argName, customErrorClass);
assertTypeNumber(arg, argName, customErrorClass);
assertTypeObject(arg, argName, customErrorClass);
assertTypeArray(arg, argName, customErrorClass);
isTypeof(value, typeString)
isObject(arg);
isArray(arg);
isNull(arg);
isUndefined(arg)
Thank You
Development sponsored by razorUX