1.3.0 • Published 4 years ago

@g2a/request-id v1.3.0

Weekly downloads
9
License
MIT
Repository
github
Last release
4 years ago

@g2a/request-id

npm

Library providing utility functions for manipulating and generating Hierarchical Request IDs.

Installation

$ npm i @g2a/request-id

Basic methods

The following methods are useful in everyday applications.

generateIncomingId()

(baseId?: string) => string;

Generates an incoming ID based on a provided base ID. If base ID is not provided or is invalid, generates it from scratch.

Use this function to generate a new ID based on one received in the request from an external service. ID generated by this function should be attached to all related log entries and should be used to create Outgoing IDs assigned to all subsequential outgoing requests.

Example of use with Express.js:

const logger = new Logger();

// Generate new incoming id for each incoming request
app.use((req, res, next) => {
  res.locals.requestId = generateIncomingId(req.get("request-id"));
  next();
});

app.get("/some-endpoint", (req, res) => {
  // Attach previously generated id to log entries
  logger.trace({
    message: "Some very interesting message",
    requestId: res.locals.requestId
  });

  res.sendStatus(204);
});

generateOutgoingId()

(id: string) => string;

Generates an outgoing ID based on a provided base ID. If base ID is not provided or is invalid, generates ID from scratch.

Use this function to generate unique ID each time you make a request to any external service.

Example of use with:

app.post("/do-something", (req, res) => {
  // See how it's generated in the example to  the`generateIncomingId()` method
  const currentRequestId = res.locals.requestId;

  request.post({
    url: "http://some-external-service/api",
    headers: {
      "Request-Id": generateOutgoingId(currentRequestId)
    }
  });
});

Advanced methods

Using the following methods requires a better understanding of the Hierarchical Request Id format. These methods could be useful if you need to do some more advanced manipulations on request IDs.

isValid()

(id: string) => boolean;

Checks if the provided ID conforms to Hierarchical Request ID standard.

isIncoming()

(id: string) => boolean;

Checks if the provided ID is an Incoming ID.

isOutgoing()

(id: string) => boolean;

Checks if the provided ID is an Outgoing ID (but not a bare Root ID).

isRoot()

(id: string) => boolean;

Checks if the provided ID is a Root ID.

generateRootId()

() => string;

Generates a new root ID.

generateOverflowedId()

(id: string) => string;

Generates an overflowed ID based on provided one. If provided id is invalid, generates it from scratch.

extractRootId()

(id: string) => string | null;

Extracts root ID from the provided hierarchical request ID. If root ID cannot be extracted (ID is invalid) returns null instead.