@@ -11,7 +11,7 @@ const textDecoder = new TextDecoder();
1111 */
1212export class Socket {
1313 readonly socketPath : string ;
14- readonly connection : Promise < Deno . UnixConn > ;
14+ private readonly connect : ( ) => Promise < Deno . UnixConn > ;
1515
1616 /**
1717 * Create a new UNIX socket instance.
@@ -29,20 +29,17 @@ export class Socket {
2929 ) ;
3030
3131 this . socketPath = socketPath ;
32- this . connection = socketOptions . connect ( { path : socketPath , transport : 'unix' } ) ;
32+ this . connect = ( ) => socketOptions . connect ( { path : this . socketPath , transport : 'unix' } ) ;
3333 }
3434
35- /**
36- * Write to the socket.
37- *
38- * @param path Path to write to, ex. `/api/info`
39- * @param init Init options for the request
40- */
41- private async write (
35+ public async request (
4236 path : string ,
43- init : SocketRequestInit
44- ) : Promise < number > {
45- const connection = await this . connection ;
37+ init : SocketRequestInit = {
38+ method : method . GET ,
39+ headers : { }
40+ }
41+ ) : Promise < Response > {
42+ const connection = await this . connect ( ) ;
4643
4744 const headers = Object . assign ( {
4845 Connection : 'close' ,
@@ -57,24 +54,19 @@ export class Socket {
5754 ] ;
5855
5956 const requestPayload = headerLines . join ( "\r\n" ) ;
60- return connection . write ( textEncoder . encode ( requestPayload ) ) ;
61- }
62-
63- public async request (
64- path : string ,
65- init : SocketRequestInit = {
66- method : method . GET ,
67- headers : { }
68- }
69- ) : Promise < Response > {
70- const connection = await this . connection ;
71- await this . write ( path , init ) ;
57+ await connection . write ( textEncoder . encode ( requestPayload ) ) ;
7258
7359 let buffer = new Uint8Array ( )
7460 for await ( const chunk of connection . readable ) {
7561 buffer = new Uint8Array ( [ ...buffer , ...chunk ] )
7662 }
7763
64+ try {
65+ connection . close ( ) ;
66+ } catch ( error ) {
67+ // We assume that the connection got already closed.
68+ }
69+
7870 return parse ( textDecoder . decode ( buffer ) ) ;
7971 }
8072}
0 commit comments