npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@egomobile/microservices

v2.0.0

Published

Shared library for microservices, written for Node.js

Downloads

306

Readme

npm

@egomobile/microservices

Shared library for microservices, written for Node.js, in TypeScript.

Install

Execute the following command from your project folder, where your package.json file is stored:

npm install --save @egomobile/microservices

Usage

Auth

Passwords

Hash passwords with bcrypt:

import { checkPassword, checkPasswordSync, hashPassword, hashPasswordSync } from '@egomobile/microservices';

const hash1 = await hashPassword('test');
const doesMatch1 = await checkPassword('test', hash1);  // true

const hash2 = hashPasswordSync('test');
const doesMatch2 = checkPasswordSync('Test', hash2);  // false

JWT

Sign and verify JSON Web Tokens:

import { signJWT, verifyJWT } from '@egomobile/microservices';

interface IUserToken {
    uuid: string;
}

const jwt = signJWT({
    uuid: 'cb246b52-b8cd-4916-bfad-6bfc43845597'
});

const decodedToken = verifyJWT<IUserToken>(jwt);
Express

Use predefined Express middleware to verify and decode JWTs:

import express from 'express';
import { withJWT } from '@egomobile/microservices';

const app = express();

app.get('/', withJWT(), async (request, response) => {
    // decoded, valid user token is stored in:
    // request.userToken
});

app.listen(4242, () => {
    console.log('Service is listening ...');
});
Azure AD

You can connect with Azure AD, by using passport and passport-azure-ad modules:

import express from 'express';
import { setupAppForAzureAD } from '@egomobile/microservices';

const app = express();

const { withAzureADBearer } = setupAppForAzureAD(app);

app.get('/', withAzureADBearer(), async (request, response) => {
    // get decoded token
    const authInfo: any = request.authInfo;

    return response.json(authInfo);
});

app.listen(4242, () => {
    console.log('Service is listening ...');
});

Constants

| Name | Description | Example | |----------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------| | APPLICATION_INSIGHTS_KEY | Application Insights key. | dd7589fc-1cf9-413e-bf6c-aa1253858b55 | | AZURE_AD_AUDIENCE | Azure AD audience. | 6b3c51b9-7cc0-4327-a901-e5b889efbbaa | | AZURE_AD_CLIENT_ID | App ID for Azure AD. | 6b3c51b9-7cc0-4327-a901-e5b889efbbaa | | AZURE_AD_IDENTITY_METADATA | Identity metadata. | https://myazuread.b2clogin.com/myazuread.onmicrosoft.com/my_policy/v2.0/.well-known/openid-configuration | | AZURE_AD_IS_B2C | true if Azure AD is running in B2C context. | true | | AZURE_AD_LOGGING_LEVEL | Azure ADlogging level. Possible values are error, info or warn. | info | | AZURE_AD_PASS_REQ_TO_CALLBACK | true if Azure AD request should be passed to callback. | false | | AZURE_AD_POLICY_NAME | Azure AD policy name. | my_policy | | AZURE_STORAGE_CONNECTION_* | The string of the connection to the storage. | DefaultEndpointsProtocol=https;....windows.net | | AZURE_STORAGE_CONNECTION_*_CONTAINER | The name of the underlying container. | my_container | | AZURE_AD_VALIDATE_ISSUER | true if Azure AD issuer should be validated or not. | false | | BCRYPT_ROUNDS | The number of rounds for bcrypt hashing. Default: 10 | 12 | | EMAIL_FROM | The email from field. | [email protected] | | EMAIL_HOST | The host for sending mail. | smtp.office365.com | | EMAIL_PASSWORD | The email password for authentication. | <some secure password> | | EMAIL_PORT | The port for sending mail. | 587 | | EMAIL_SECURE | Should the email be send encryted? | false | | EMAIL_USER | The email user for authentication. | [email protected] | | EMAIL_TO | The email to field. | [email protected] | | JWT_SECRET | The secret for signing and validating JWT. | mySecretJWTSecret | | LOCAL_DEVELOPMENT | true if app running in local development context or not. | false | | LOG_LEVEL | The name of the logging level. | debug | | MONGO_DB | The name of the database to connect to. | myDatabase | | MONGO_IS_LAZY | If true, MongoDatabase will throw an error, if not enough configuration data is available, the first time an instance of it is used, instead the time an instance of it is created. | true | | MONGO_URL | The connection URL. | mongodb://mongo.example.com:27017 | | NATS_CLUSTER_ID | The name of the cluster, that contains all microservices. | my-cluster | | NATS_GROUP | The name of the pod group / Kubernetes deployment. | my-service-or-deployment | | NATS_URL | The URL to the NATS server. | http://my-nats-service:4222 | | POD_NAME | The name of the pod. This should come as imported metadata from Kubernetes. | my-service-or-deployment-xcsgbxv |

Diagnostics

The library uses winston as logger:

import { logger } from '@egomobile/microservices';

logger.info('Hello e.GO!', {
    file: __filename
});

Application Insights

Setup Application Insights:

import { setupApplicationInsights } from '@egomobile/microservices';

// you must define 'APPLICATION_INSIGHTS_KEY'
// and must not be in local development context
setupApplicationInsights();

Express

Schema

Use schema namespace, which is a link to embedded joi module, and build-in middlewares to validate input.

import { schema, withDataURI, withSchema } from '@egomobile/microservices';

interface IMySchema {
    email?: string;
    first_name: string;
    last_name: string;
}

const mySchema = schema.object({
    email: schema.string().strict().trim().email().optional()
    first_name: schema.string().strict().trim().min(1).required()
    last_name: schema.string().strict().trim().min(1).required()
}).required();


// withSchema() will automatically add
// middleware, created by express.json()
// with a limit of 128 MB
app.post('/user/register', withSchema(mySchema), async (request, response) => {
    const body: IMySchema = request.body;

    // ...
});

// withDataURI() will automatically add middlewares
// to parse the input
app.put('/user/image', withDataURI(), async (request, response) => {
    // data:<MIME>;base64,<BASE64-DATA>

    const mime = request.headers['content-type'] as string;  // <MIME>
    const body: Buffer = request.body;  // decoded <BASE64-DATA>

    // ...
});

MongoDB

Use MongoDatabase class, which has simple support to handle MongoDB connections:

import { MongoDatabase } from '@egomobile/microservices';

const mongo = new MongoDatabase();
await mongoDb.connect();

// insert
await mongo.insert('myCollection', [{
    uuid: '8d41b8fc-2110-4b05-91ff-0a40c007be9d',
    last_name: 'Kloubert',
    first_name: 'Marcel'
}, {
    uuid: '90b7191d-44ce-43c9-a6e3-b777a8b9c8a6',
    last_name: 'M',
    first_name: 'Tanja'
}]);

// find
const docs = await mongo.find('myCollection', {
    first_name: 'Tanja'
});

// count
const docsCount = await mongo.count('myCollection', {
    first_name: 'Marcel'
});

mongo.disconnect();

NATS

Connect to a NATS server:

import { stan } from '@egomobile/microservices';

await stan.connect();
stan.exitOnClose();

Listener

Listen for events:

import { NatsListener } from '@egomobile/microservices';

interface IMyEvent {
    foo: string;
    bar: number;
}

const myEventListener = new NatsListener<IMyEvent>('my.event');

myEventListener.onMessage = async (context) => {
    // handle message in context.message of type IMyEvent
};

myEventListener.listen();

Publisher

Publish events:

import { NatsPublisher } from '@egomobile/microservices';

interface IMyEvent {
    foo: string;
    bar: number;
}

const myEventPublisher = new NatsPublisher<IMyEvent>('my.event');

await myEventPublisher.publish({
    foo: "TM+MK",
    bar: 42
});

Documentation

The API documentation can be found here.