1
1
import { Elysia } from "elysia"
2
2
import { getIP } from "./getip"
3
3
import { defaultOptions } from "../constants"
4
+ import { logger } from "./logger"
5
+
4
6
import type { Options } from "../types"
5
7
6
8
export const plugin = ( userOptions ?: Partial < Options > ) => ( app : Elysia ) => {
@@ -13,23 +15,38 @@ export const plugin = (userOptions?: Partial<Options>) => (app: Elysia) => {
13
15
new Elysia ( {
14
16
name : "elysia-ip" ,
15
17
} ) . derive ( { as : "global" } , ( { request } ) : { ip : string } => {
16
- if ( ! options . headersOnly && globalThis . Bun ) {
17
- const socketAddress = options . injectServer ( app ) ?. requestIP ( request )
18
- if ( socketAddress ) return { ip : socketAddress . address }
19
- else {
20
- console . log (
21
- `Elysia server is not initialized. Make sure to call Elyisa.listen()` ,
22
- )
23
- console . log ( `use injectServer to inject Server instance` )
18
+ serverIP: {
19
+ if ( ! options . headersOnly && globalThis . Bun ) {
20
+ const server = options . injectServer ( app )
21
+ if ( ! server ) {
22
+ logger (
23
+ "plugin" ,
24
+ "Elysia server is not initialized. Make sure to call Elyisa.listen()" ,
25
+ )
26
+ logger ( "plugin" , "use injectServer to inject Server instance" )
27
+ break serverIP
28
+ }
29
+
30
+ if ( ! server . requestIP ) {
31
+ logger ( "plugin" , "server.requestIP is null" )
32
+ logger ( "plugin" , "Please check server instace" )
33
+ break serverIP
34
+ }
35
+
36
+ const socketAddress = server . requestIP ( request )
37
+ logger ( "plugin" , "socketAddress" , socketAddress )
38
+ if ( ! socketAddress ) {
39
+ logger (
40
+ "plugin" ,
41
+ `ip from server.requestIP return ${ typeof socketAddress } ` ,
42
+ )
43
+ break serverIP
44
+ }
45
+ return { ip : socketAddress . address }
24
46
}
25
47
}
26
48
return {
27
- ip :
28
- getIP ( request . headers , options . checkHeaders ) ||
29
- ( function ( ) {
30
- console . log ( "Failed to get ip from header!" )
31
- return ""
32
- } ) ( ) ,
49
+ ip : getIP ( request . headers , options . checkHeaders ) || "" ,
33
50
}
34
51
} ) ,
35
52
)
0 commit comments