Skip to content

Commit 0427da3

Browse files
authored
Merge pull request google#53 from google/node-route
Use async hooks from node, fix route comment
2 parents aaf20d9 + 614314d commit 0427da3

7 files changed

Lines changed: 10239 additions & 44 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
const hooks = require('async_hooks')
2+
const store = new Map();
3+
4+
const hook = hooks.createHook({
5+
init: (asyncId, _, triggerAsyncId) => {
6+
if (store.has(triggerAsyncId)) {
7+
store.set(asyncId, store.get(triggerAsyncId))
8+
}
9+
},
10+
destroy: (asyncId) => {
11+
if (store.has(asyncId)) {
12+
store.delete(asyncId)
13+
}
14+
}
15+
});
16+
17+
hook.enable();
18+
19+
const createContext = (data) => {
20+
store.set(hooks.executionAsyncId(), data);
21+
return data;
22+
};
23+
24+
const getContext = () => {
25+
return store.get(hooks.executionAsyncId());
26+
};
27+
28+
module.exports = { createContext, getContext };

nodejs/sqlcommenter-nodejs/packages/sqlcommenter-knex/index.js

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
const {hasComment} = require('./util');
1616
const provider = require('./provider');
17+
const hook = require('./hooks');
1718

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

66-
// TODO: Perhaps remove uuid as it is highly ephemeral?
67-
// comments.uuid = obj.__knexQueryUid;
68-
6967
if (Knex.__middleware__) {
70-
const req = Knex.__req__;
71-
72-
comments['route'] = req.path;
73-
74-
// TODO: Clear out __req__ for the next usage.
75-
// Knex.__req__ = null;
68+
const context = hook.getContext();
69+
if (context && context.req) {
70+
comments.route = context.req.route.path;
71+
}
7672
}
7773

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

152148
return (req, res, next) => {
153-
149+
data = { req: req };
150+
hook.createContext(data);
154151
Knex.__middleware__ = true;
155-
Knex.__req__ = req;
156-
157-
// TODO: Perhaps grab the view/controller name.
158-
// Usually req.route.path is useful enough to correlate
159-
// where/what source code originates.
160152
next();
161153
}
162154
}

0 commit comments

Comments
 (0)