Skip to content

Commit a55b0cd

Browse files
authored
Add setConsumer helper functions (#111)
* Add setConsumer functions * Add tests
1 parent 5718b52 commit a55b0cd

File tree

18 files changed

+122
-82
lines changed

18 files changed

+122
-82
lines changed

src/adonisjs/index.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,12 @@ import type { HttpContext } from "@adonisjs/core/http";
33
import type { ApitallyConfig } from "../common/types.js";
44
export type { ApitallyConfig, ApitallyConsumer } from "../common/types.js";
55

6-
export const defineConfig = (config: ApitallyConfig) => {
6+
export function defineConfig(config: ApitallyConfig) {
77
return config;
8-
};
8+
}
99

10-
export const captureError = (error: unknown, ctx: HttpContext) => {
10+
export function captureError(error: unknown, ctx: HttpContext) {
1111
if (error instanceof Error) {
1212
ctx.apitallyError = error;
1313
}
14-
};
14+
}

src/adonisjs/provider.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ export default class ApitallyProvider {
4141
}
4242
}
4343

44-
const listRoutes = (router: Router) => {
44+
function listRoutes(router: Router) {
4545
const routes = router.toJSON();
4646
const paths: Array<PathInfo> = [];
4747
for (const domain in routes) {
@@ -57,9 +57,9 @@ const listRoutes = (router: Router) => {
5757
}
5858
}
5959
return paths;
60-
};
60+
}
6161

62-
const getVersions = (appVersion?: string) => {
62+
function getVersions(appVersion?: string) {
6363
const versions = [["nodejs", process.version.replace(/^v/, "")]];
6464
const adonisJsVersion = getPackageVersion("@adonisjs/core");
6565
const apitallyVersion = getPackageVersion("../..");
@@ -73,4 +73,4 @@ const getVersions = (appVersion?: string) => {
7373
versions.push(["app", appVersion]);
7474
}
7575
return Object.fromEntries(versions);
76-
};
76+
}

src/express/index.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
export type { ApitallyConsumer } from "../common/types.js";
2-
export { useApitally } from "./middleware.js";
1+
export type { ApitallyConfig, ApitallyConsumer } from "../common/types.js";
2+
export { setConsumer, useApitally } from "./middleware.js";

src/express/middleware.ts

Lines changed: 29 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,10 @@ declare module "express" {
2626
}
2727
}
2828

29-
export const useApitally = (
29+
export function useApitally(
3030
app: Express | Router,
3131
config: ApitallyConfig & { basePath?: string },
32-
) => {
32+
) {
3333
const client = new ApitallyClient(config);
3434
const middleware = getMiddleware(app, client);
3535
app.use(middleware);
@@ -43,9 +43,9 @@ export const useApitally = (
4343
}
4444
};
4545
setTimeout(() => setStartupData(), 500);
46-
};
46+
}
4747

48-
const getMiddleware = (app: Express | Router, client: ApitallyClient) => {
48+
function getMiddleware(app: Express | Router, client: ApitallyClient) {
4949
let errorHandlerConfigured = false;
5050

5151
return (req: Request, res: Response, next: NextFunction) => {
@@ -185,9 +185,9 @@ const getMiddleware = (app: Express | Router, client: ApitallyClient) => {
185185
next();
186186
}
187187
};
188-
};
188+
}
189189

190-
const getRoutePath = (req: Request) => {
190+
function getRoutePath(req: Request) {
191191
if (!req.route) {
192192
return;
193193
}
@@ -199,9 +199,9 @@ const getRoutePath = (req: Request) => {
199199
}
200200
}
201201
return req.route.path;
202-
};
202+
}
203203

204-
const getRouterPath = (stack: any[], baseUrl: string) => {
204+
function getRouterPath(stack: any[], baseUrl: string) {
205205
const routerPaths: string[] = [];
206206
while (stack && stack.length > 0) {
207207
const routerLayer = stack.find(
@@ -240,9 +240,16 @@ const getRouterPath = (stack: any[], baseUrl: string) => {
240240
}
241241
}
242242
return routerPaths.filter((path) => path !== "/").join("");
243-
};
243+
}
244+
245+
export function setConsumer(
246+
req: Request,
247+
consumer: ApitallyConsumer | string | null | undefined,
248+
) {
249+
req.apitallyConsumer = consumer || undefined;
250+
}
244251

245-
const getConsumer = (req: Request) => {
252+
function getConsumer(req: Request) {
246253
if (req.apitallyConsumer) {
247254
return consumerFromStringOrObject(req.apitallyConsumer);
248255
} else if (req.consumerIdentifier) {
@@ -254,9 +261,9 @@ const getConsumer = (req: Request) => {
254261
return consumerFromStringOrObject(req.consumerIdentifier);
255262
}
256263
return null;
257-
};
264+
}
258265

259-
const extractExpressValidatorErrors = (responseBody: any) => {
266+
function extractExpressValidatorErrors(responseBody: any) {
260267
try {
261268
const errors: ValidationError[] = [];
262269
if (
@@ -278,9 +285,9 @@ const extractExpressValidatorErrors = (responseBody: any) => {
278285
} catch (error) {
279286
return [];
280287
}
281-
};
288+
}
282289

283-
const extractCelebrateErrors = (responseBody: any) => {
290+
function extractCelebrateErrors(responseBody: any) {
284291
try {
285292
const errors: ValidationError[] = [];
286293
if (responseBody && responseBody.validation) {
@@ -305,9 +312,9 @@ const extractCelebrateErrors = (responseBody: any) => {
305312
} catch (error) {
306313
return [];
307314
}
308-
};
315+
}
309316

310-
const extractNestValidationErrors = (responseBody: any) => {
317+
function extractNestValidationErrors(responseBody: any) {
311318
try {
312319
const errors: ValidationError[] = [];
313320
if (responseBody && Array.isArray(responseBody.message)) {
@@ -323,20 +330,20 @@ const extractNestValidationErrors = (responseBody: any) => {
323330
} catch (error) {
324331
return [];
325332
}
326-
};
333+
}
327334

328-
const subsetJoiMessage = (message: string, key: string) => {
335+
function subsetJoiMessage(message: string, key: string) {
329336
const messageWithKey = message
330337
.split(". ")
331338
.find((message) => message.includes(`"${key}"`));
332339
return messageWithKey ? messageWithKey : message;
333-
};
340+
}
334341

335-
const getAppInfo = (
342+
function getAppInfo(
336343
app: Express | Router,
337344
basePath?: string,
338345
appVersion?: string,
339-
): StartupData => {
346+
): StartupData {
340347
const versions: Array<[string, string]> = [
341348
["nodejs", process.version.replace(/^v/, "")],
342349
];
@@ -360,4 +367,4 @@ const getAppInfo = (
360367
versions: Object.fromEntries(versions),
361368
client: "js:express",
362369
};
363-
};
370+
}

src/fastify/index.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
export type { ApitallyConsumer } from "../common/types.js";
2-
export { default as apitallyPlugin } from "./plugin.js";
1+
export type { ApitallyConfig, ApitallyConsumer } from "../common/types.js";
2+
export { default as apitallyPlugin, setConsumer } from "./plugin.js";

src/fastify/plugin.ts

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ const apitallyPlugin: FastifyPluginAsync<ApitallyConfig> = async (
164164
});
165165
};
166166

167-
const getAppInfo = (routes: PathInfo[], appVersion?: string) => {
167+
function getAppInfo(routes: PathInfo[], appVersion?: string) {
168168
const versions = [["nodejs", process.version.replace(/^v/, "")]];
169169
const fastifyVersion = getPackageVersion("fastify");
170170
const apitallyVersion = getPackageVersion("../..");
@@ -182,9 +182,16 @@ const getAppInfo = (routes: PathInfo[], appVersion?: string) => {
182182
versions: Object.fromEntries(versions),
183183
client: "js:fastify",
184184
};
185-
};
185+
}
186186

187-
const getConsumer = (request: FastifyRequest) => {
187+
export function setConsumer(
188+
request: FastifyRequest,
189+
consumer: ApitallyConsumer | string | null | undefined,
190+
) {
191+
request.apitallyConsumer = consumer || undefined;
192+
}
193+
194+
function getConsumer(request: FastifyRequest) {
188195
if (request.apitallyConsumer) {
189196
return consumerFromStringOrObject(request.apitallyConsumer);
190197
} else if (request.consumerIdentifier) {
@@ -196,18 +203,18 @@ const getConsumer = (request: FastifyRequest) => {
196203
return consumerFromStringOrObject(request.consumerIdentifier);
197204
}
198205
return null;
199-
};
206+
}
200207

201-
const getResponseTime = (reply: FastifyReply) => {
208+
function getResponseTime(reply: FastifyReply) {
202209
if (reply.elapsedTime !== undefined) {
203210
return reply.elapsedTime;
204211
} else if ((reply as any).getResponseTime !== undefined) {
205212
return (reply as any).getResponseTime();
206213
}
207214
return 0;
208-
};
215+
}
209216

210-
const extractAjvErrors = (message: string): ValidationError[] => {
217+
function extractAjvErrors(message: string): ValidationError[] {
211218
const regex =
212219
/(?<=^|, )((?:headers|params|query|querystring|body)[/.][^ ]+)(?= )/g;
213220
const matches: { match: string; index: number }[] = [];
@@ -229,7 +236,7 @@ const extractAjvErrors = (message: string): ValidationError[] => {
229236
type: "",
230237
};
231238
});
232-
};
239+
}
233240

234241
export default fp(apitallyPlugin, {
235242
name: "apitally",

src/h3/index.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
export type { ApitallyConsumer } from "../common/types.js";
2-
export { apitallyPlugin } from "./plugin.js";
1+
export type { ApitallyConfig, ApitallyConsumer } from "../common/types.js";
2+
export { apitallyPlugin, setConsumer } from "./plugin.js";

src/h3/plugin.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,9 +131,9 @@ export const apitallyPlugin = definePlugin<ApitallyConfig>((app, config) => {
131131
{
132132
statusCode,
133133
responseTime: responseTime / 1000,
134-
headers: responseHeaders
135-
? convertHeaders(Object.fromEntries(responseHeaders.entries()))
136-
: [],
134+
headers: convertHeaders(
135+
Object.fromEntries(responseHeaders.entries()),
136+
),
137137
size: responseSize,
138138
body: responseBody,
139139
},
@@ -179,6 +179,13 @@ export const apitallyPlugin = definePlugin<ApitallyConfig>((app, config) => {
179179
);
180180
});
181181

182+
export function setConsumer(
183+
event: H3Event,
184+
consumer: ApitallyConsumer | string | null | undefined,
185+
) {
186+
event.context.apitallyConsumer = consumer || undefined;
187+
}
188+
182189
function getConsumer(event: H3Event) {
183190
const consumer = event.context.apitallyConsumer;
184191
if (consumer) {

src/hono/index.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
export type { ApitallyConsumer } from "../common/types.js";
2-
export { useApitally } from "./middleware.js";
1+
export type { ApitallyConfig, ApitallyConsumer } from "../common/types.js";
2+
export { setConsumer, useApitally } from "./middleware.js";

src/hono/middleware.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,14 @@ function getMiddleware(client: ApitallyClient): MiddlewareHandler {
137137
};
138138
}
139139

140-
export function getConsumer(c: Context) {
140+
export function setConsumer(
141+
c: Context,
142+
consumer: ApitallyConsumer | string | null | undefined,
143+
) {
144+
c.set("apitallyConsumer", consumer || undefined);
145+
}
146+
147+
function getConsumer(c: Context) {
141148
const consumer = c.get("apitallyConsumer");
142149
if (consumer) {
143150
return consumerFromStringOrObject(consumer);

src/koa/index.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
export type { ApitallyConsumer } from "../common/types.js";
2-
export { useApitally } from "./middleware.js";
1+
export type { ApitallyConfig, ApitallyConsumer } from "../common/types.js";
2+
export { setConsumer, useApitally } from "./middleware.js";

0 commit comments

Comments
 (0)