1.0.1 • Published 5 years ago
request-guid v1.0.1
request-guid
generate unique guid for request contains remote/local IP address.
Install
npm install --save request-guid
# or var yarn
yarn add request-guid
Usage
- generate a guid (encode):
import { createEncoder } from 'request-guid'; // create a encoder at first const encoder = createEncoder('0123456789abcdef' /* secret */); // encode const guid = encoder('127.0.0.1' /* remote address */, '1.1.1.1' /* local address */) // -> xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx
parse guid (decode):
import { createDecoder } from 'request-guid'; // create a decoder at first, the secret must same to the encoder // which generates the guid const decoder = createDecoder('0123456789abcdef', /* secret */); // decode const info = decoder('xxxxxxxx-xxxxxxxx-xxxxxxxx-xxxxxxxx'); // -> { index: number, timestamp: number, localIP: number, remoteIP: number }
as an express middleware:
import express from 'express'; import { requestGuid } from 'request-guid/middlewares/express'; const app = express() app.use(requestGuid({ secret: '0123456789abcdef', /* required */ header: 'X-Request-Id', /* optional, http header name, default is 'X-Request-Id' */ name: 'id', /* optional, set the req[name] as guid, default is 'id' */ }))
Notes
- the
secret
must be one of:- 16-bytes hex string
- 8-bytes Uint8Array (or Buffer in Node.js)
- the
local address
andremote address
only could be aIPv4
address, or a 4-bytes integer, if not, it will be replaced by0
(for local address), and0xffffffff
(for remote address). - the info decoded contains 4 fields:
index
,timestamp
,localIP
,remoteIP
, all of these kind arenumber
, and: -index
: the request order, it is the auto-incremental 4-bytes integer -timestamp
: the second of the current time -localIP/remoteIP
: the 4-bytes integer of the ip address, you can useint2ip
to format it.
API
request-guid
:export type Encoder = (localIP: string, remoteIP: string) => string; export interface GuidInfo { index: number; timestamp: number; localIP: number; remoteIP: number; } export interface FriendlyGuidInfo { index: number; timestamp: string; // ISO string localIP: string; remoteIP: string; } export type Decoder = { (guid: string): GuidInfo; (guid: string, friendly: true): FriendlyGuidInfo; } export declare function createEncoder(secret: string | Buffer): Encoder; export declare function createDecoder(secret: string | Buffer, friendly?: boolean): Decoder; // utils export declare function ip2int(ip: string): number; export declare function int2ip(int: number): string;
request-guid/lib/middlewares/types
:export interface MiddlewareOptions { secret: string | Buffer; header?: string; name?: string; }
request-guid/lib/middlewares/express
:import { RequestHandler } from 'express'; export declare function requestGuid(options: MiddlewareOptions): RequestHandler;
License
MIT