UNPKG

node-lens

Version:

Lens is a lightweight developer tool for Node.js apps that lets you log, view, and debug requests and other activity in real time — inspired by Laravel Telescope.

102 lines (98 loc) 2.56 kB
import { __dirname, getQueryByRequestId, getRecentQueries, getRecentRequests, getRequestById, getRequestId, logQuery, logRequest, runWithRequestId } from "../chunk-7EU2ZT4R.mjs"; // src/adapters/express.ts import express from "express"; import path from "path"; // src/logger/proxy.ts function createProxy(client, options) { return new Proxy(client, { get(target, prop, receiver) { const original = Reflect.get(target, prop, receiver); if (typeof original !== "function") { return original; } return function(...args) { if (typeof prop === "string" && options.methods.includes(prop)) { logQuery({ query: args[0], durationMs: 100 }); } return original.apply(target, args); }; } }); } // src/adapters/express.ts async function middleware(req, res, next) { const requestId = crypto.randomUUID(); runWithRequestId(requestId, () => { const memoryUsageMb = process.memoryUsage().rss / 1024 / 1024; const start = process.hrtime(); res.on("finish", async () => { const end = process.hrtime(start); logRequest({ method: req.method, status: res.statusCode, path: req.path, requestId, ip: req.ip ?? "-", memoryUsageMb, durationMs: end[0] * 1e3 + end[1] / 1e6, request: { headers: req.headers, body: req.body }, response: { headers: res.getHeaders() // TODO: get response body } }); }); next(); }); } function routes() { const router = express.Router(); const uiPath = path.resolve(__dirname, "..", "ui"); router.use(express.static(uiPath)); router.get("/api/requests", (_, res) => { res.json(getRecentRequests()); }); router.get("/api/requests/:id", (req, res) => { const { id } = req.params; res.json(getRequestById(id)); }); router.get("/api/queries", (_, res) => { res.json(getRecentQueries()); }); router.get("/api/queries/:id", (req, res) => { const { id } = req.params; res.json(getQueryByRequestId(id)); }); router.use("/{*splat}", (_, res) => { res.sendFile(path.join(uiPath, "index.html")); }); return router; } function lens(options = {}) { const path2 = options.path || "/lens"; const router = express.Router(); router.get("/lens-config", (_, res) => { res.json({ path: path2 }); }); router.use(path2, routes()); router.use(middleware); return router; } export { createProxy, getRequestId, lens };