Skip to content
This repository was archived by the owner on May 29, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions nodejs/sqlcommenter-nodejs/packages/sqlcommenter-knex/hooks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const hooks = require('async_hooks')
const store = new Map();

const hook = hooks.createHook({
init: (asyncId, _, triggerAsyncId) => {
if (store.has(triggerAsyncId)) {
store.set(asyncId, store.get(triggerAsyncId))
}
},
destroy: (asyncId) => {
if (store.has(asyncId)) {
store.delete(asyncId)
}
}
});

hook.enable();

const createContext = (data) => {
store.set(hooks.executionAsyncId(), data);
return data;
};

const getContext = () => {
return store.get(hooks.executionAsyncId());
};

module.exports = { createContext, getContext };
22 changes: 7 additions & 15 deletions nodejs/sqlcommenter-nodejs/packages/sqlcommenter-knex/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

const {hasComment} = require('./util');
const provider = require('./provider');
const hook = require('./hooks');

const defaultFields = {
'route': true,
Expand Down Expand Up @@ -63,16 +64,11 @@ exports.wrapMainKnex = (Knex, include={}, options={}) => {
db_driver: `knex:${knexVersion}`
};

// TODO: Perhaps remove uuid as it is highly ephemeral?
// comments.uuid = obj.__knexQueryUid;

if (Knex.__middleware__) {
const req = Knex.__req__;

comments['route'] = req.path;

// TODO: Clear out __req__ for the next usage.
// Knex.__req__ = null;
const context = hook.getContext();
if (context && context.req) {
comments.route = context.req.route.path;
}
}

// Add trace context to comments, depending on the current provider.
Expand Down Expand Up @@ -150,13 +146,9 @@ exports.wrapMainKnexAsMiddleware = (Knex, include=null, options) => {
exports.wrapMainKnex(Knex, include, options);

return (req, res, next) => {

data = { req: req };
hook.createContext(data);
Knex.__middleware__ = true;
Knex.__req__ = req;

// TODO: Perhaps grab the view/controller name.
// Usually req.route.path is useful enough to correlate
// where/what source code originates.
next();
}
}
Loading