Skip to content

Commit bbbedc6

Browse files
author
Hack.bg Admin
committed
refactor(Http,Tcp): less dependence on deps.ts
1 parent 620a0cd commit bbbedc6

5 files changed

Lines changed: 23 additions & 30 deletions

File tree

lib/context/Http.ts

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
1-
import type { ClientRequest, ServerResponse } from '../deps.ts';
2-
import { HttpServer } from '../deps.ts';
3-
import { tcpAddr } from './Tcp.ts';
1+
import type { ClientRequest, ServerResponse } from 'node:http';
2+
import { Server as HttpServer } from 'node:http';
43
import { Ports } from './Port.ts';
54
import { Log } from './Log.ts';
65
import { Fn } from '../format.ts';
@@ -58,13 +57,13 @@ export interface Http extends Fn.Takes<[Http.Context]> {}
5857
* ...modelSpecificRoutes); }
5958
*
6059
* */
61-
function Http (name?: string, ...routes: Http.Handler[]): Http;
60+
function Http (name?: string, ...routes: Http[]): Http;
61+
function Http (...routes: Http[]): Http;
6262
function Http (...routes: unknown[]) {
6363
let name = 'Http';
64-
if (typeof routes[0] === 'string') name = routes.shift();
64+
if (typeof routes[0] === 'string') name = routes.shift() as string;
6565
return Fn.Name(name, httpRouter, { routes })
66-
async function httpRouter (context) {
67-
const { req, res, debug = console.debug, error = console.error } = context;
66+
async function httpRouter (context: Http.Context) {
6867
for (const route of routes) {
6968
if (route && typeof route === 'function') {
7069
const result = await route(context);
@@ -81,7 +80,7 @@ namespace Http {
8180
export type Server = HttpServer;
8281
export type Request = ClientRequest;
8382
export type Response = ServerResponse;
84-
export type Context = { path?: string, method?: Method, body?: string };
83+
export type Context = Log & { req: Request, res: Response };
8584
export type Method = 'GET'|'PUT'|'PATCH'|'POST'|'DELETE'|'HEAD'|'OPTIONS';
8685
export const Method = (m: Method, ...f: Http[]): Http => Fn.Name(`Method ${m}`,
8786
function methodHandler (r: Context) {
@@ -92,18 +91,18 @@ namespace Http {
9291
export const Patch = (prefix?: string, ..._: Http[]) => method('PATCH', prefix, ..._);
9392
export const Post = (prefix?: string, ..._: Http[]) => method('POST', prefix, ..._);
9493
export const Delete = (prefix?: string, ..._: Http[]) => method('DELETE', prefix, ..._);
95-
function method (m: string, ...args: unknown[]) {
94+
function method (m: Method, ...args: unknown[]) {
9695
if (typeof args[0] === 'string') return Prefix(args[0], method(m, ...args.slice(1)));
97-
return Method(m, ...args);
96+
return Method(m, ...args as Http[]);
9897
}
9998
export const Prefix = (p: string, ...f: Http[]): Http => Fn.Name(`Prefix ${p}`,
10099
function prefixHandler (r: Context) {
101100
if (r.req.url === p) return Fn.Pipe(...f)(r)
102101
}, { ...f, path: p });
103-
export const Guard = (code: number, ...f: Http[]): Http => Fn.Name(`Guard ${c}`,
102+
export const Guard = (code: number, ...f: Http[]): Http => Fn.Name(`Guard ${code}`,
104103
async function guardHandler (r: Context) {
105104
const x = await Fn.Pipe(...f)(r);
106-
if (!x) throw Object.assign(new Error(c), { http: code })
105+
if (!x) throw Object.assign(new Error(`HTTP ${code}`), { http: code })
107106
}, { ...f, code });
108107
export function Listen (l: string|number|URL, ...routes: Http[]) {
109108
if (typeof l === 'number') l = `localhost:${l}`;
@@ -112,25 +111,28 @@ namespace Http {
112111
const handler = Http(...routes);
113112
return Fn.Name(`Listen (${hostname}:${port})`, httpListen, { hostname, port, ...routes });
114113
function httpListen <P extends Ports & Log> (context: P = Ports(Log()) as P): Server {
115-
const { ports = {}, log = console.log, debug = console.debug } = context;
114+
const { ports = {}, debug = console.debug } = context;
116115
const server = new HttpServer();
117116
const portState = ports[port] = { url: l, server };
118117
server.on('request', onRequest);
119118
server.on('close', onClose);
120119
return new Promise((resolve, reject)=>{
121120
server.once('error', reject);
122-
server.listen(Number(port), hostname as string, () => {
121+
debug('Starting listener on', port);
122+
server.listen(Number(port), hostname as string, onListen);
123+
function onListen () {
123124
server.off('error', reject);
124125
debug('Listening on', hostname, port);
125126
resolve(server)
126-
});
127+
}
127128
});
128129
async function onClose () {
130+
debug('Stopping listener');
129131
if (ports[port] === portState) {
130132
delete ports[port];
131133
}
132134
}
133-
async function onRequest (req, res) {
135+
async function onRequest (req: Request, res: Response) {
134136
debug('REQ', req.method.padEnd(6), req.url)
135137
let code = 404;
136138
let result = undefined;

lib/context/Port.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1+
import { Socket } from 'node:net';
12
import { Fn, Error } from '../format.ts';
2-
import { Socket } from '../deps.ts';
33
/** Keep track of port assignments. */
44
export interface Ports<T = unknown> { ports: Record<number, T> };
55
/** Add ports to context. */

lib/context/Tcp.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import type { Fn } from '../index.ts';
2-
import type { Socket } from '../deps.ts';
3-
import { createTcpServer, createConnection } from '../deps.ts';
2+
import type { Socket } from 'node:net';
3+
import { createServer, createConnection } from 'node:net';
44
export function Listen (at: number|string|URL, handler: Fn<[Socket]>) {
55
const { port, hostname } = tcpAddr(at);
6-
const server = createTcpServer(handler);
6+
const server = createServer(handler);
77
server.on('connecton', handler);
88
return new Promise((resolve, reject) => {
99
server.once('error', reject);

lib/context/Tui.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1+
import { stdin, stdout } from 'node:process';
12
import type { Timed } from '../index.ts';
2-
import { stdin, stdout } from '../deps.ts';
33
export default Tui;
44
/** Launch a terminal user interface. */
55
function Tui <T extends Tui> (state: T = {} as T): T {

lib/deps.ts

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,6 @@ export { spawn as spawnImpl } from 'node:child_process';
88
export type { ChildProcess } from 'node:child_process';
99
export type { Buffer } from 'node:buffer';
1010

11-
export { createServer as createTcpServer
12-
, createConnection
13-
, Server as TcpServer
14-
, Socket } from 'node:net';
15-
16-
export { createServer as createHttpServer
17-
, Server as HttpServer } from 'node:http';
18-
export type { ClientRequest, ServerResponse } from 'node:http';
19-
2011
export const webcrypto =
2112
globalThis.crypto ?? (await import('node:crypto')).webcrypto;
2213

0 commit comments

Comments
 (0)