Socket
Socket
Sign inDemoInstall

common-services

Package Overview
Dependencies
7
Maintainers
1
Versions
48
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    common-services

A module to gather very common services.


Version published
Maintainers
1
Created

Readme

Source

common-services

A module to gather very common services.

GitHub license Coverage Status

This module contains various common injectable services I use into a lot of applications.

API

Functions

initCodeGenerator(services)Promise.<function()> | Promise.<function()>

Instantiate the codeGenerator service

initCounter(services)Promise.<function()>

Instantiate the counter service

initDelay(services)Promise.<Object>

Instantiate the delay service

initImporter(path)Promise.<Object>

Allow to import ES modules.

initLock(services)Promise.<Object>

Instantiate the lock service

initLog(services)Promise.<function()>

Instantiate the logging service

initRandom(services)Promise.<function()>

Instantiate the random service

initResolve(path)Promise.<string>

Allow to resolve a path with the module system.

initTime(services)Promise.<function()>

Instantiate the time service

initCodeGenerator(services) ⇒ Promise.<function()> | Promise.<function()>

Instantiate the codeGenerator service

Kind: global function

ParamTypeDefaultDescription
servicesObjectThe services to inject
[services.CHARS_SET]ObjectEXPLICIT_CHARSAn optional char set to pick cars into
[services.random]ObjectMath.randomAn optional random function to replace the Math.random one used by default
[services.log]ObjectnoopAn optional logging function

Example

import initCodeGenerator from 'common-services/dist/codeGenerator';

const codeGenerator = await initCodeGenerator({
  log: console.log.bind(console),
});

initCodeGenerator~codeGenerator([length]) ⇒ Promise.<String>

Returns a random code

Kind: inner method of initCodeGenerator
Returns: Promise.<String> - A promise of the generated code

ParamTypeDefaultDescription
[length]Number6An optional custon code length (defaults to 6)

Example

console.log([
  codeGenerator(),
  codeGenerator(),
  codeGenerator(),
]);
// Prints: ABCDEF,GHJKMN,PRSTUV

initCounter(services) ⇒ Promise.<function()>

Instantiate the counter service

Kind: global function
Returns: Promise.<function()> - A promise of the counter function

ParamTypeDefaultDescription
servicesObjectThe services to inject
[services.COUNTER]ObjectDEFAULT_COUNTERAn optional configuration object
[services.log]ObjectnoopAn optional logging function

Example

import initCounter from 'common-services/dist/counter';

const counter = await initCounter({
  COUNTER: { firstCount: 1 },
  log: console.log.bind(console),
});

initCounter~counter() ⇒ Promise.<number>

Returns the current count and increment the counter

Kind: inner method of initCounter
Returns: Promise.<number> - A promise of the current count
Example

console.log([
  counter(),
  counter(),
  counter(),
]);
// Prints: 1,2,3

initDelay(services) ⇒ Promise.<Object>

Instantiate the delay service

Kind: global function
Returns: Promise.<Object> - A promise of the delay service

ParamTypeDefaultDescription
servicesObjectThe services to inject
[services.log]functionnoopA logging function

Example

import initDelay from 'common-services/dist/delay';

const delay = await initDelay({
  log: console.log.bind(console)
});

initDelay~create(delay) ⇒ Promise

Create a new delay

Kind: inner method of initDelay
Returns: Promise - A promise to be resolved after that delay or rejected if it is cancelled.

ParamTypeDescription
delayNumberThe delay in ms

Example

await delay.create(1000);
console.log('1000 ms elapsed!');

initDelay~clear(promise) ⇒ Promise

Cancel an earlier created delay

Kind: inner method of initDelay
Returns: Promise - A promise resolved when cancellation is done.

ParamTypeDescription
promisePromiseThe promise of the delay to cancel

Example

try {
  const delayPromise = delay.create(1000);
  await Promise.all(delayPromise, delay.clear(delayPromise));
  console.log('1000 ms elapsed!');
} catch (err) {
  if(err.code != 'E_DELAY_CLEARED') {
    trow err;
  }
  console.log('Cancelled!'));
}
// Prints: Cancelled!

initImporter(path) ⇒ Promise.<Object>

Allow to import ES modules.

Kind: global function
Returns: Promise.<Object> - A promise of an imported module.

ParamTypeDescription
pathstringThe module path

initLock(services) ⇒ Promise.<Object>

Instantiate the lock service

Kind: global function
Returns: Promise.<Object> - A promise of the lock service

ParamTypeDefaultDescription
servicesObjectThe services to inject
[services.LOCKS_MAP]MapA map to store le current locks (optional)
[services.LOCK_TIMEOUT]NumberInfitinyThe timeout in milliseconds for the lock to be released.
[services.log]functionA logging function
[services.delay]ObjectA delay service like the common-services one

Example

import initLog from 'common-services/dist/log';
import initDelayService from 'common-services/dist/delay';
import initLock from 'common-services/dist/lock';
import ms from 'ms';
import winston from 'winston';
import debug from 'debug';

const log = await initLogService({
  logger: winston,
  debug: debug('myapp'),
});
const delay = await initDelayService({ log });
const lock = await initLock ({ LOCK_TIMEOUT: ms('5s'), delay, log });


run();

async function run() {
  // The following async jobs are done sequentially
  // if they have the same `resourceKey` value
  await Promise.all(asynTasks.map(async (asyncTask) => {
    await lock.take(asyncTask.resourceKey);

    await myAsyncStuff1(asyncTask);
    await myAsyncStuff2(asyncTask);
    await myAsyncStuff3(asyncTask);

   lock.release(asyncTask.resourceKey);
  });
}

initLock~take(key) ⇒ Promise

Take the lock on the given resource key

Kind: inner method of initLock
Returns: Promise - A promise to be resolved when the lock is gained or rejected if the lock release timeout is reached.

ParamTypeDescription
keyStringA unique key for the locked resource

initLock~release(key) ⇒ void

Release the lock on the given resource key

Kind: inner method of initLock

ParamTypeDescription
keyStringA unique key for the resource to release

initLog(services) ⇒ Promise.<function()>

Instantiate the logging service

Kind: global function
Returns: Promise.<function()> - A promise of the logging function

ParamTypeDescription
servicesObjectThe services to inject
services.loggerObjectThe logger object that output the logs

Example

import initLog from 'common-services/dist/log';
import debug from 'debug';
import winston from 'winston';

const log = await initLog({
  logger: winston,
  debug: debug('myapp'),
 });

initLog~log(type, ...args) ⇒ void

Logging function

Kind: inner method of initLog

ParamTypeDescription
typeStringLog type
...args*Log contents

Example

log('debug', 'Luke, I am your father!')

initRandom(services) ⇒ Promise.<function()>

Instantiate the random service

Kind: global function
Returns: Promise.<function()> - A promise of the random function

ParamTypeDefaultDescription
servicesObjectThe services to inject
[services.log]ObjectnoopA logging function

Example

import initRandom from 'common-services/dist/random';

const random = await initRandom({
  log: console.log.bind(console),
});

initRandom~random() ⇒ number

Returns a new random number

Kind: inner method of initRandom
Returns: number - The random number
Example

random()
// Prints: 0.3141592653589793

initResolve(path) ⇒ Promise.<string>

Allow to resolve a path with the module system.

Kind: global function
Returns: Promise.<string> - A promise of a fully qualified module path

ParamTypeDescription
pathstringThe serializable constants to gather

initTime(services) ⇒ Promise.<function()>

Instantiate the time service

Kind: global function
Returns: Promise.<function()> - A promise of the time function

ParamTypeDefaultDescription
servicesObjectThe services to inject
[services.log]ObjectnoopA logging function

Example

import initTime from 'common-services/dist/time';

const time = await initTime({
  log: console.log.bind(console),
});

initTime~time() ⇒ number

Returns the current timestamp

Kind: inner method of initTime
Returns: number - The current timestamp
Example

time()
// Prints: 1326585600000

Authors

License

MIT

Keywords

FAQs

Last updated on 24 Feb 2024

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc