Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

http-request-context

Package Overview
Dependencies
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

http-request-context - npm Package Compare versions

Comparing version 0.0.2 to 0.0.3

93

index.js

@@ -1,11 +0,92 @@

const createNameSpace = require('./namespace')
const asyncHooks = require('async_hooks')
const ns = createNameSpace('__HTTP_REQUEST_CONTEXT__')
const contexts = {}
const rootAsyncIdQueueMap = {}
const INTERVAL = 1000
const ID_TIMEOUT = 60000
ns.middleware = (req, res, next) => {
ns.init()
next()
// delete asyncId map 60s ago every second
const interval = () => {
setTimeout(interval, INTERVAL)
const now = Date.now()
Object.keys(contexts).forEach((id, index) => {
// skip first TCPWRAP asyncId
if (index && now - contexts[id].__tm > ID_TIMEOUT) {
delete contexts[id]
}
})
}
setTimeout(interval, INTERVAL)
module.exports = ns
const findRootId = (id) => {
if (!id) {
return
}
if (contexts[id]) {
if (contexts[id].data) {
return id
}
return findRootId(contexts[id].id)
}
}
const removeAsyncId = id => {
Object.keys(contexts).forEach(cacheId => {
if (contexts[cacheId].id === id) {
delete contexts[cacheId]
removeAsyncId(cacheId)
}
})
}
asyncHooks.createHook({
init (asyncId, type, triggerAsyncId) {
contexts[asyncId] = {
id: asyncHooks.executionAsyncId(),
__tm: Date.now()
}
if (type === 'TCPWRAP') {
// app start rootId
rootAsyncIdQueueMap[asyncId] = []
}
const rootID = findRootId(asyncId)
if (rootID) {
rootAsyncIdQueueMap[rootID].push(asyncId)
}
},
destroy (asyncId) {
if (rootAsyncIdQueueMap[asyncId]) {
delete contexts[asyncId]
rootAsyncIdQueueMap[asyncId].forEach(id => {
delete contexts[id]
})
delete rootAsyncIdQueueMap[asyncId]
}
if (!findRootId(asyncId)) {
delete contexts[asyncId]
}
}
}).enable()
module.exports = {
middleware: (req, res, next) => {
const executionAsyncId = asyncHooks.executionAsyncId()
contexts[executionAsyncId].data = {}
rootAsyncIdQueueMap[executionAsyncId] = []
next()
},
set: (key, value) => {
const rootId = findRootId(asyncHooks.executionAsyncId())
if (rootId) {
Object.assign(contexts[rootId].data, { [key]: value })
}
},
get: (key) => {
const rootId = findRootId(asyncHooks.executionAsyncId())
if (rootId) {
return contexts[rootId].data[key]
}
}
}

2

package.json
{
"name": "http-request-context",
"version": "0.0.2",
"version": "0.0.3",
"description": "Store context in http middleware lifecycle.",

@@ -5,0 +5,0 @@ "main": "index.js",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc