Skip to content

Commit

Permalink
Fix getting versions for app info (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
itssimon committed Jan 18, 2024
1 parent 686f732 commit bd2325e
Show file tree
Hide file tree
Showing 15 changed files with 91 additions and 27 deletions.
14 changes: 14 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 19 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@
"import": "./lib/esm/nestjs/index.js",
"require": "./lib/cjs/nestjs/index.cjs",
"types": "./lib/types/nestjs/index.d.ts"
}
},
"./package.json": "./package.json"
},
"eslintConfig": {
"parser": "@typescript-eslint/parser",
Expand All @@ -93,7 +94,13 @@
},
"root": true
},
"prettier": {
"printWidth": 80
},
"babel": {
"ignore": [
"**/__mocks__"
],
"presets": [
[
"@babel/preset-env",
Expand Down Expand Up @@ -124,6 +131,7 @@
]
],
"plugins": [
"babel-plugin-transform-import-meta",
[
"transform-require-extensions",
{
Expand Down Expand Up @@ -151,9 +159,17 @@
"preset": "ts-jest",
"testEnvironment": "node",
"transform": {
"^.+\\.ts$": "ts-jest",
"^.+\\.ts$": [
"ts-jest",
{
"useESM": true
}
],
"^.+\\.js$": "babel-jest"
},
"modulePathIgnorePatterns": [
"<rootDir>/lib"
],
"moduleNameMapper": {
"^(\\.{1,2}/.*)\\.js$": "$1"
},
Expand Down Expand Up @@ -223,6 +239,7 @@
"@typescript-eslint/eslint-plugin": "^6.11.0",
"@typescript-eslint/parser": "^6.11.0",
"babel-jest": "^29.7.0",
"babel-plugin-transform-import-meta": "^2.2.1",
"babel-plugin-transform-require-extensions": "^2.0.1",
"celebrate": "^15.0.3",
"class-transformer": "^0.5.1",
Expand Down
4 changes: 4 additions & 0 deletions src/common/__mocks__/packageVersions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function getPackageVersion(name: string): string | null {
return "0.0.0";
}
4 changes: 2 additions & 2 deletions src/common/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import { randomUUID } from "crypto";

import { KeyCacheBase, KeyRegistry } from "./keyRegistry.js";
import { Logger, getLogger } from "./logging.js";
import { isValidClientId, isValidEnv } from "./paramValidation.js";
import RequestLogger from "./requestLogger.js";
import {
ApitallyConfig,
AppInfo,
AppInfoPayload,
RequestsDataPayload,
} from "./types.js";
import { isValidClientId, isValidEnv } from "./utils.js";
import ValidationErrorLogger from "./validationErrorLogger.js";

const SYNC_INTERVAL = 60000; // 60 seconds
Expand Down Expand Up @@ -211,7 +211,7 @@ export class ApitallyClient {
};
this.requestsDataQueue.push([Date.now(), newPayload]);

const failedItems = [];
const failedItems: [number, RequestsDataPayload][] = [];
while (this.requestsDataQueue.length > 0) {
const queueItem = this.requestsDataQueue.shift();
if (queueItem) {
Expand Down
10 changes: 10 additions & 0 deletions src/common/packageVersions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { createRequire } from "module";

export function getPackageVersion(name: string): string | null {
try {
const _require = createRequire(import.meta.url);
return _require(`${name}/package.json`).version || null;
} catch (error) {
return null;
}
}
8 changes: 0 additions & 8 deletions src/common/utils.ts → src/common/paramValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,3 @@ export function isValidEnv(env: string): boolean {
const regexExp = /^[\w-]{1,32}$/;
return regexExp.test(env);
}

export function getPackageVersion(name: string): string | null {
try {
return require(`${name}/package.json`).version || null; // eslint-disable-line @typescript-eslint/no-var-requires
} catch (error) {
return null;
}
}
4 changes: 2 additions & 2 deletions src/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ export type PathInfo = {
};

export type AppInfo = {
paths: Array<PathInfo>;
versions: Map<string, string>;
paths: PathInfo[];
versions: Record<string, string>;
client: string;
};

Expand Down
8 changes: 5 additions & 3 deletions src/express/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { performance } from "perf_hooks";

import { ApitallyClient } from "../common/client.js";
import { KeyInfo } from "../common/keyRegistry.js";
import { getPackageVersion } from "../common/packageVersions.js";
import { ApitallyConfig, AppInfo, ValidationError } from "../common/types.js";
import { getPackageVersion } from "../common/utils.js";
import listEndpoints from "./listEndpoints.js";

declare module "express" {
Expand Down Expand Up @@ -172,7 +172,9 @@ const subsetJoiMessage = (message: string, key: string) => {
};

const getAppInfo = (app: Express, appVersion?: string): AppInfo => {
const versions: Array<[string, string]> = [["nodejs", process.version]];
const versions: Array<[string, string]> = [
["nodejs", process.version.replace(/^v/, "")],
];
const expressVersion = getPackageVersion("express");
const apitallyVersion = getPackageVersion("../..");
if (expressVersion) {
Expand All @@ -186,7 +188,7 @@ const getAppInfo = (app: Express, appVersion?: string): AppInfo => {
}
return {
paths: listEndpoints(app),
versions: new Map(versions),
versions: Object.fromEntries(versions),
client: "js:express",
};
};
9 changes: 5 additions & 4 deletions src/fastify/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import fp from "fastify-plugin";

import { ApitallyClient } from "../common/client.js";
import { KeyInfo } from "../common/keyRegistry.js";
import { getPackageVersion } from "../common/packageVersions.js";
import { ApitallyConfig, PathInfo, ValidationError } from "../common/types.js";
import { getPackageVersion } from "../common/utils.js";

declare module "fastify" {
interface FastifyReply {
Expand Down Expand Up @@ -33,7 +33,6 @@ const apitallyPlugin: FastifyPluginAsync<ApitallyConfig> = async (
? routeOptions.method
: [routeOptions.method];
methods.forEach((method) => {
routeOptions.onSend;
if (!["HEAD", "OPTIONS"].includes(method.toUpperCase())) {
routes.push({
method: method.toUpperCase(),
Expand Down Expand Up @@ -92,7 +91,9 @@ const apitallyPlugin: FastifyPluginAsync<ApitallyConfig> = async (
};

const getAppInfo = (routes: PathInfo[], appVersion?: string) => {
const versions: Array<[string, string]> = [["nodejs", process.version]];
const versions: Array<[string, string]> = [
["nodejs", process.version.replace(/^v/, "")],
];
const fastifyVersion = getPackageVersion("fastify");
const apitallyVersion = getPackageVersion("../..");
if (fastifyVersion) {
Expand All @@ -106,7 +107,7 @@ const getAppInfo = (routes: PathInfo[], appVersion?: string) => {
}
return {
paths: routes,
versions: new Map(versions),
versions: Object.fromEntries(versions),
client: "js:fastify",
};
};
Expand Down
8 changes: 5 additions & 3 deletions src/koa/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import Koa from "koa";

import { ApitallyClient } from "../common/client.js";
import { KeyInfo } from "../common/keyRegistry.js";
import { getPackageVersion } from "../common/packageVersions.js";
import { ApitallyConfig, AppInfo, PathInfo } from "../common/types.js";
import { getPackageVersion } from "../common/utils.js";

export const useApitally = (app: Koa, config: ApitallyConfig) => {
const client = new ApitallyClient(config);
Expand Down Expand Up @@ -56,7 +56,9 @@ const getConsumer = (ctx: Koa.Context) => {
};

const getAppInfo = (app: Koa, appVersion?: string): AppInfo => {
const versions: Array<[string, string]> = [["nodejs", process.version]];
const versions: Array<[string, string]> = [
["nodejs", process.version.replace(/^v/, "")],
];
const koaVersion = getPackageVersion("koa");
const apitallyVersion = getPackageVersion("../..");
if (koaVersion) {
Expand All @@ -70,7 +72,7 @@ const getAppInfo = (app: Koa, appVersion?: string): AppInfo => {
}
return {
paths: listEndpoints(app),
versions: new Map(versions),
versions: Object.fromEntries(versions),
client: "js:koa",
};
};
Expand Down
2 changes: 1 addition & 1 deletion tests/common/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ describe("Client", () => {
env: ENV,
});
jest.spyOn(client.logger, "error").mockImplementation(() => {});
client.setAppInfo({ paths: [], versions: new Map(), client: "js:test" });
client.setAppInfo({ paths: [], versions: {}, client: "js:test" });

await new Promise((resolve) => setTimeout(resolve, 10));
expect(client["syncIntervalId"]).toBeUndefined();
Expand Down
11 changes: 10 additions & 1 deletion tests/express/app.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
import {
afterEach,
beforeEach,
describe,
expect,
it,
jest,
} from "@jest/globals";
import { Express } from "express";
import request from "supertest";

import { ApitallyClient } from "../../src/common/client.js";
import { API_KEY, mockApitallyHub } from "../utils.js";
import { getAppWithCelebrate, getAppWithValidator } from "./app.js";

jest.mock("../../src/common/packageVersions.ts");

const testCases = [
{
name: "Middleware for Express with celebrate",
Expand Down
11 changes: 10 additions & 1 deletion tests/fastify/app.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import { afterEach, beforeEach, describe, expect, it } from "@jest/globals";
import {
afterEach,
beforeEach,
describe,
expect,
it,
jest,
} from "@jest/globals";
import { FastifyInstance } from "fastify";
import request from "supertest";

import { ApitallyClient } from "../../src/common/client.js";
import { API_KEY, mockApitallyHub } from "../utils.js";
import { getApp } from "./app.js";

jest.mock("../../src/common/packageVersions.ts");

const testCases = [
{
name: "Plugin for Fastify",
Expand Down
2 changes: 2 additions & 0 deletions tests/koa/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import { ApitallyClient } from "../../src/common/client.js";
import { API_KEY, mockApitallyHub } from "../utils.js";
import { getAppWithKoaRoute, getAppWithKoaRouter } from "./app.js";

jest.mock("../../src/common/packageVersions.ts");

const testCases = [
{
name: "Middleware for Koa with koa-router",
Expand Down
2 changes: 2 additions & 0 deletions tests/nestjs/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import { ApitallyApiKeyGuard } from "../../src/nestjs/auth.js";
import { API_KEY, mockApitallyHub } from "../utils.js";
import { getApp } from "./app.js";

jest.mock("../../src/common/packageVersions.ts");

describe("Middleware for NestJS", () => {
let app: INestApplication;
let appTest: request.SuperTest<request.Test>;
Expand Down

0 comments on commit bd2325e

Please sign in to comment.