Skip to content

Commit f489ae6

Browse files
committed
complete 2.0.0 version!!!
1 parent 2fba8ad commit f489ae6

File tree

14 files changed

+349
-357
lines changed

14 files changed

+349
-357
lines changed

README.md

Lines changed: 87 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -15,24 +15,27 @@
1515
* [`Router()`](#router)
1616
* [`mount(path, router)`](#mountpath-router)
1717
* [`METHOD(task)`](#methodtask)
18-
* [Helpers on `Request`](#helpers-on-request)
19-
* [`request. de_originalUrl`: string](#request-de_originalurl-string)
20-
* [`request. de_parsedUrl`: Url](#request-de_parsedurl-url)
21-
* [`request. de_queryString`: object](#request-de_querystring-object)
22-
* [`request. de_response`: Respond](#request-de_response-respond)
23-
* [`request. de_method`: string](#request-de_method-string)
24-
* [`request. de_headers`: object](#request-de_headers-object)
25-
* [`request. de_taskList`: Task[]](#request-de_tasklist-task)
26-
* [`request. de_getIp()`: () => string](#request-de_getip-string)
27-
* [`request.share`: {}](#requestshare)
28-
* [Helpers on `Response`](#helpers-on-response)
29-
* [`response. de_request`: Request](#response-de_request-request)
30-
* [`response. de_setHeader(object)`: (object) => Respond](#response-de_setheaderobject-object-respond)
31-
* [`response. de_setStatus(code)`: (code: number) => Response](#response-de_setstatuscode-code-number-response)
32-
* [`response. de_send(body)`: (body?) => Response](#response-de_sendbody-body-response)
3318
* [`listen(port)`](#listenport)
3419
* [`close()`](#close)
3520
* [`getListeningAddress()`](#getlisteningaddress)
21+
* [Helpers on `Request`](#helpers-on-request)
22+
* [`request.innerRequest`: IncomingMessage](#requestinnerrequest-incomingmessage)
23+
* [`request.innerResponse`: ServerResponse](#requestinnerresponse-serverresponse)
24+
* [`request.originalUrl`: string](#requestoriginalurl-string)
25+
* [`request.parsedUrl`: Url](#requestparsedurl-url)
26+
* [`request.response`: Respond](#requestresponse-respond)
27+
* [`request.method`: string](#requestmethod-string)
28+
* [`request.headers`: object](#requestheaders-object)
29+
* [`request.taskList`: Task[]](#requesttasklist-task)
30+
* [`request.ip`: string](#requestip-string)
31+
* [`request.share`: {}](#requestshare)
32+
* [Helpers on `Response`](#helpers-on-response)
33+
* [`response.request`: Request](#responserequest-request)
34+
* [`response.innerRequest`: IncomingMessage](#responseinnerrequest-incomingmessage)
35+
* [`response.innerResponse`: ServerResponse](#responseinnerresponse-serverresponse)
36+
* [`response.setHeader(object)`: (object) => Respond](#responsesetheaderobject-object-respond)
37+
* [`response.setStatus(code)`: (code: number) => Response](#responsesetstatuscode-code-number-response)
38+
* [`response.send(body)`: (body?) => Response](#responsesendbody-body-response)
3639
* [Build and Test](#build-and-test)
3740
* [Build](#build)
3841
* [Test](#test)
@@ -100,12 +103,12 @@ For a specific http request, system will give you an integrated **`TPT`**. And t
100103

101104
# How to use
102105

103-
Use `npm` to install `@sevenryze/server`, then import the only exported class.
106+
Use `npm` to install `@sevenryze/server-router`, then import the only exported class.
104107

105108
```
106-
import { Router } from "@sevenryze/server"
109+
import { Router } from "@sevenryze/server-router"
107110
// Or commonjs
108-
const { Router } = require("@sevenryze/server");
111+
const { Router } = require("@sevenryze/server-router");
109112
110113
let router = new Router();
111114
```
@@ -158,7 +161,7 @@ Want to know why? see my blog, if there are... 🤡
158161

159162
```
160163
// sync task
161-
router.get( (request, response, next) => {
164+
router.get((request, response, next) => {
162165
// Do something.
163166
164167
response.send();
@@ -173,78 +176,116 @@ router.get(async (request, response, next) => {
173176
})
174177
```
175178

176-
## Helpers on `Request`
179+
## `listen(port)`
177180

178-
### `request. de_originalUrl`: string
181+
- port: The port listening to.
179182

180-
Original, unprocessed request url.
183+
Listen the specific port.
181184

182-
### `request. de_parsedUrl`: Url
185+
If there are under tests case or would like to get a temp port, you should use number `0` as the argument.
183186

184-
The parsed http url, see https://nodejs.org/dist/latest-v9.x/docs/api/url.html#url_url_strings_and_url_objects for more info.
187+
If port is omitted or is 0, the operating system will assign an arbitrary unused port, which can be retrieved by using Router.getListeningAddress().port after the 'listening' event has been emitted.
188+
189+
```
190+
router.listen(7777);
191+
```
192+
193+
## `close()`
194+
195+
Close the server.
196+
197+
```
198+
router.close();
199+
```
200+
201+
## `getListeningAddress()`
202+
203+
Get the bounding server address info.
204+
205+
# Helpers on `Request`
206+
207+
## `request.innerRequest`: IncomingMessage
208+
209+
The underlying http request.
210+
211+
## `request.innerResponse`: ServerResponse
212+
213+
The underlying http response.
214+
215+
## `request.originalUrl`: string
216+
217+
Original, unprocessed request url.
185218

186-
### `request. de_queryString`: object
219+
## `request.parsedUrl`: Url
187220

188-
The query string key-value pairs parsed into object format.
221+
The parsed http url, see https://nodejs.org/dist/latest-v9.x/docs/api/url.html#url_url_strings_and_url_objects for more info.
189222

190-
### `request. de_response`: Respond
223+
## `request.response`: Respond
191224

192225
Point to the accompanied Response object.
193226

194-
### `request. de_method`: string
227+
## `request.method`: string
195228

196229
The request http method.
197230

198-
### `request. de_headers`: object
231+
## `request.headers`: object
199232

200233
The http headers parsed into object format.
201234

202-
### `request. de_taskList`: Task[]
235+
## `request.taskList`: Task[]
203236

204237
The tasks waiting for this request.
205238

206-
### `request. de_getIp()`: () => string
239+
## `request.ip`: string
207240

208241
Get the client ip and be able to handle behind proxy case.
209242

210243
```js
211-
request.de_getIp();
244+
request.ip;
212245
// => "127.0.0.1"
213246
```
214247

215-
### `request.share`: {}
248+
## `request.share`: {}
216249

217-
The app context variable for simply share state between tasks.
250+
The app context variable for simply share states between tasks.
218251

219-
## Helpers on `Response`
252+
# Helpers on `Response`
220253

221-
### `response. de_request`: Request
254+
## `response.request`: Request
222255

223256
Points to the accompanied request object.
224257

225-
### `response. de_setHeader(object)`: (object) => Respond
258+
## `response.innerRequest`: IncomingMessage
259+
260+
The underlying http request.
261+
262+
## `response.innerResponse`: ServerResponse
263+
264+
The underlying http response.
226265

227-
- object <string> - Object used to set the headers, such as { Accept: "text/plain", "X-API-Key": "dde" }.
266+
## `response.setHeader(object)`: (object) => Respond
267+
268+
- `object: Headers` - Object used to set the headers, such as { Accept: "text/plain", "X-API-Key": "dde" }.
228269

229270
Set header `key` to its `value`. If the `Content-Type` field is going to be set, this method will automatically turn the value to extensional form, eg."html" to the standard mime forms "text/html", and add the charset if it can be matched in mime-db package.
230271

231272
Return the this object, aka. Respond to make chain-able calls available.
232273

233274
```js
234-
response.de_setHeader({ Accept: "text/plain", "X-API-Key": "xmt" });
275+
response.setHeader({ Accept: "text/plain", "X-API-Key": "xmt" });
235276
// => Accept: "text/plain"
236277
// => X-API-Key: "xmt"
237-
response.de_setHeader({ "Content-Type": "json" });
278+
response.setHeader({ "Content-Type": "json" });
238279
// => Content-Type: "application/json; charset=utf-8"
239-
response.de_setHeader({ "Content-Type": "html" });
280+
response.setHeader({ "Content-Type": "html" });
240281
// => Content-Type: "text/html; charset=utf-8"
241-
response.de_setHeader({ "Content-Type": "bin" });
282+
response.setHeader({ "Content-Type": "bin" });
242283
// => Content-Type: "application/octet-stream"
243284
```
244285

245-
### `response. de_setStatus(code)`: (code: number) => Response
286+
## `response.setStatus(code)`: (code: number) => Response
246287

247-
- code <number> - Http status code number such as "404"
288+
- `code: number` - Http status code number such as "404"
248289

249290
Set the status `code` of the response.
250291

@@ -254,9 +295,9 @@ Return this object for chain-able calls.
254295
response.setStatus(404);
255296
```
256297

257-
### `response. de_send(body)`: (body?) => Response
298+
## `response.send(body)`: (body?) => Response
258299

259-
- body <string | object | buffer> - Can be a string such as `"some string"`, an object such as `{some: "haha"}` and a buffer such as `new Buffer("some buffer")`.
300+
- `body: string | object | buffer` - Can be a string such as `"some string"`, an object such as `{some: "haha"}` and a buffer such as `new Buffer("some buffer")`.
260301

261302
Send response to the remote client, and this method will terminate the underlying socket session.
262303

@@ -266,32 +307,6 @@ response.send({ some: "json" });
266307
response.send("<p>some html</p>");
267308
```
268309

269-
## `listen(port)`
270-
271-
- port: The port listening to.
272-
273-
Listen the specific port.
274-
275-
If there are under tests case or would like to get a temp port, you should use number `0` as the argument.
276-
277-
If port is omitted or is 0, the operating system will assign an arbitrary unused port, which can be retrieved by using Router.getListeningAddress().port after the 'listening' event has been emitted.
278-
279-
```
280-
router.listen(7777);
281-
```
282-
283-
## `close()`
284-
285-
Close the server.
286-
287-
```
288-
router.close();
289-
```
290-
291-
## `getListeningAddress()`
292-
293-
Get the bounding server address info.
294-
295310
# Build and Test
296311

297312
## Build

lib/index.ts

Lines changed: 27 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,35 @@
11
import { createServer, IncomingMessage, Server, ServerResponse } from "http";
22
import { AddressInfo } from "net";
33
import staticServe from "serve-static";
4-
import { parse } from "url";
54
import { Debug } from "./helper/debugger";
65
import { RouterError } from "./helper/router-error";
7-
import { IRequest, IResponse, ITask } from "./interface";
8-
import { requestProto } from "./prototype/request";
9-
import { responseProto } from "./prototype/response";
6+
import { Request } from "./prototype/request";
7+
import { Response } from "./prototype/response";
108
import { buildRunList } from "./runList";
119
import { schedule } from "./schedule";
1210

1311
const debug = Debug(__filename);
1412

15-
export type IRequest = IRequest;
16-
export type IResponse = IResponse;
17-
export type ITask = ITask;
13+
export type Request = Request;
14+
export type Response = Response;
1815

19-
export function serveStatic(root: string, options?: staticServe.ServeStaticOptions) {
20-
return (staticServe(root, options) as unknown) as ITask;
16+
export interface ITask {
17+
(request: Request, response: Response, next: () => void): void;
18+
19+
mountHttpMethod?: string;
20+
21+
// strimPath = requestPath - absolutePath
22+
strimPath?: string;
23+
}
24+
25+
export function serveStatic(root: string, options?: staticServe.ServeStaticOptions): ITask {
26+
const middleware = staticServe(root, options);
27+
28+
return (request, response, next) => {
29+
request.innerRequest.url = request.trimmedUrl;
30+
31+
middleware(request.innerRequest as any, response.innerResponse as any, next);
32+
};
2133
}
2234

2335
export class Router {
@@ -158,42 +170,17 @@ export class Router {
158170

159171
// This is actual handler of the incoming message.
160172
private incomingRequestHandler = (request: IncomingMessage, response: ServerResponse): void => {
161-
const requestAppend: any = {};
162-
const responseAppend: any = {};
163-
164173
debug(`Get method: ${request.method} on url: ${request.url}`);
165174

166-
// Protect the original URL from unintentional polluting.
167-
requestAppend.de_originalUrl = request.url;
168-
169-
// Store the url-related info.
170-
requestAppend.de_parsedUrl = parse(request.url!, true);
171-
requestAppend.de_queryString = requestAppend.de_parsedUrl.query;
172-
173-
requestAppend.de_method = request.method;
174-
requestAppend.de_headers = request.headers;
175-
176-
// This taskList is the main ordered task list the current request matched.
177-
// Important!
178-
requestAppend.de_taskList = [];
179-
180-
// Point to each other.
181-
requestAppend.de_response = response;
182-
responseAppend.de_request = request;
183-
184-
// Merge properties of our Request and Response prototypes
185-
// to the incoming request and response objects.
186-
Object.assign(request, requestAppend, requestProto);
187-
Object.assign(response, responseAppend, responseProto);
175+
const perfectRequest = new Request(request, response);
176+
const perfectResponse = new Response(response, request);
177+
perfectRequest.response = perfectResponse;
178+
perfectResponse.request = perfectRequest;
188179

189180
// Build the runList.
190-
buildRunList(this, (request as unknown) as IRequest, ((request as unknown) as IRequest).de_taskList);
181+
buildRunList(this, perfectRequest, perfectRequest.taskList);
191182

192183
// Run the tasks.
193-
schedule(
194-
((request as unknown) as IRequest).de_taskList,
195-
(request as unknown) as IRequest,
196-
(response as unknown) as IResponse
197-
);
184+
schedule(perfectRequest.taskList, perfectRequest, perfectResponse);
198185
};
199186
}

0 commit comments

Comments
 (0)