Skip to content

Commit

Permalink
feat: implement ConnInfo helper (#180)
Browse files Browse the repository at this point in the history
* feat: implement ConnInfo helper

* chore: change package.json to export ConnInfo helper

* fix: lint

* remove `bun.lockb`

---------

Co-authored-by: Yusuke Wada <yusuke@kamawada.com>
  • Loading branch information
nakasyou and yusukebe authored Jul 3, 2024
1 parent fa8cb6b commit b8fb04b
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
8 changes: 8 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@
"types": "./dist/utils/*.d.ts",
"require": "./dist/utils/*.js",
"import": "./dist/utils/*.mjs"
},
"./conninfo": {
"types": "./dist/conninfo.d.ts",
"require": "./dist/conninfo.js",
"import": "./dist/conninfo.mjs"
}
},
"typesVersions": {
Expand All @@ -42,6 +47,9 @@
],
"utils/*": [
"./dist/utils/*.d.ts"
],
"conninfo": [
"./dist/conninfo.d.ts"
]
}
},
Expand Down
29 changes: 29 additions & 0 deletions src/conninfo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type { AddressInfo } from 'net'
import type { GetConnInfo } from 'hono/conninfo'
import type { HttpBindings } from './types'

/**
* ConnInfo Helper for Node.js
* @param c Context
* @returns ConnInfo
*/
export const getConnInfo: GetConnInfo = (c) => {
const bindings = (c.env.server ? c.env.server : c.env) as HttpBindings

const address = bindings.incoming.socket.address() as AddressInfo

if (!('address' in address)) {
return {
remote: {},
}
}

return {
remote: {
address: address.address,
addressType:
address.family === 'IPv4' ? 'IPv4' : address.family === 'IPv6' ? 'IPv6' : 'unknown',
port: address.port,
},
}
}
37 changes: 37 additions & 0 deletions test/conninfo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import type { AddressInfo } from 'net'
import { Hono } from 'hono'
import type { AddressType, ConnInfo } from 'hono/conninfo'
import { getConnInfo } from '../src/conninfo'

describe('ConnInfo', () => {
it('Should works', async () => {
const app = new Hono().get('/', (c) => c.json(getConnInfo(c)))

const address: AddressInfo = {
address: '0.0.0.0',
family: 'IPv4',
port: 3030,
}
expect(
await (
await app.request(
'/',
{},
{
incoming: {
socket: {
address: () => address,
},
},
}
)
).json()
).toEqual({
remote: {
address: address.address,
addressType: address.family as AddressType,
port: address.port,
},
} satisfies ConnInfo)
})
})

0 comments on commit b8fb04b

Please sign in to comment.