@@ -6,28 +6,64 @@ interface Params {
66 apiKey : string ;
77 path : string ;
88 method : string ;
9- statusCode : number | null ;
109 timeMillis : number ;
1110 query ?: string ;
11+ statusCode ?: number | null ;
1212 apilyticsIntegration ?: string ;
1313 integratedLibrary ?: string ;
1414}
1515
16+ /**
17+ * Send API analytics data to Apilytics (https://apilytics.io).
18+ * Does the sending as fire-and-forget background task.
19+ *
20+ * @param params
21+ * @param params.apiKey - The API key for your Apilytics origin.
22+ * @param params.path - Path of the user's HTTP request, e.g. '/foo/bar/123'.
23+ * @param params.method - Method of the user's HTTP request, e.g. 'GET'.
24+ * @param params.timeMillis - The amount of time in milliseconds it took
25+ * to respond to the user's request.
26+ * @param params.query - Optional query string of the user's HTTP request
27+ * e.g. 'key=val&other=123'. An empty string and null are treated equally.
28+ * Can have an optional '?' at the start.
29+ * @param params.statusCode - Status code for the sent HTTP response.
30+ * Can be omitted (or null) if the middleware could not get the status code
31+ * for the response. E.g. if the inner request handling threw an exception.
32+ * @param params.apilyticsIntegration - Name of the Apilytics integration that's
33+ * calling this, e.g. 'apilytics-node-express'.
34+ * No need to pass this when calling from user code.
35+ * @param params.integratedLibrary - Name and version of the integration that
36+ * this is used in, e.g. 'express/4.17.2'.
37+ * No need to pass this when calling from user code.
38+ *
39+ * @example
40+ *
41+ * const timer = milliSecondTimer();
42+ * const res = await handler(req);
43+ * sendApilyticsMetrics({
44+ * apikey: "<your-api-key>",
45+ * path: req.path,
46+ * query: req.queryString,
47+ * method: req.method,
48+ * statusCode: res.statusCode,
49+ * timeMillis: timer(),
50+ * });
51+ */
1652export const sendApilyticsMetrics = ( {
1753 apiKey,
1854 path,
19- query,
2055 method,
21- statusCode,
2256 timeMillis,
57+ query,
58+ statusCode,
2359 apilyticsIntegration,
2460 integratedLibrary,
2561} : Params ) : void => {
2662 const data = JSON . stringify ( {
2763 path,
2864 query : query || undefined ,
2965 method,
30- statusCode,
66+ statusCode : statusCode ?? undefined ,
3167 timeMillis,
3268 } ) ;
3369 let apilyticsVersion = `${
@@ -65,6 +101,13 @@ export const sendApilyticsMetrics = ({
65101 } ) ;
66102} ;
67103
104+ /**
105+ * Times the amount of milliseconds something takes to execute.
106+ * The timer starts when this is initially called.
107+ *
108+ * @returns A function that can be called to stop the timer.
109+ * That function's return value is the elapsed time.
110+ */
68111export const milliSecondTimer = ( ) : ( ( ) => number ) => {
69112 const startTimeNs = process . hrtime . bigint ( ) ;
70113
0 commit comments