1 | # **RE**serve
|
2 |
|
3 | <table border="0" cellpadding="2" cellspacing="0">
|
4 | <tr>
|
5 | <td valign="top">
|
6 | <strong>RE</strong>
|
7 | </td>
|
8 | <td>
|
9 | <i>duced</i></br />
|
10 | <i>levant</i></br />
|
11 | <i>verse proxy</i><br />
|
12 | <i>gexp-based</i><br />
|
13 | <i>useable</i><br />
|
14 | <strong>serve</strong>
|
15 | </td>
|
16 | </tr>
|
17 | </table>
|
18 |
|
19 | [![Travis-CI](https://travis-ci.org/ArnaudBuchholz/reserve.svg?branch=master)](https://travis-ci.org/ArnaudBuchholz/reserve#)
|
20 | [![Coverage Status](https://coveralls.io/repos/github/ArnaudBuchholz/reserve/badge.svg?branch=master)](https://coveralls.io/github/ArnaudBuchholz/reserve?branch=master)
|
21 | [![Maintainability](https://api.codeclimate.com/v1/badges/49e3adbc8f31ae2febf3/maintainability)](https://codeclimate.com/github/ArnaudBuchholz/reserve/maintainability)
|
22 | [![Package Quality](https://npm.packagequality.com/shield/reserve.svg)](https://packagequality.com/#?package=reserve)
|
23 | [![Known Vulnerabilities](https://snyk.io/test/github/ArnaudBuchholz/reserve/badge.svg?targetFile=package.json)](https://snyk.io/test/github/ArnaudBuchholz/reserve?targetFile=package.json)
|
24 | [![dependencies Status](https://david-dm.org/ArnaudBuchholz/reserve/status.svg)](https://david-dm.org/ArnaudBuchholz/reserve)
|
25 | [![devDependencies Status](https://david-dm.org/ArnaudBuchholz/reserve/dev-status.svg)](https://david-dm.org/ArnaudBuchholz/reserve?type=dev)
|
26 | [![reserve](https://badge.fury.io/js/reserve.svg)](https://www.npmjs.org/package/reserve)
|
27 | [![reserve](http://img.shields.io/npm/dm/reserve.svg)](https://www.npmjs.org/package/reserve)
|
28 | [![install size](https://packagephobia.now.sh/badge?p=reserve)](https://packagephobia.now.sh/result?p=reserve)
|
29 | [![MIT License](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
|
30 | [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2FArnaudBuchholz%2Freserve.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2FArnaudBuchholz%2Freserve?ref=badge_shield)
|
31 |
|
32 | A **lightweight** web server statically **configurable** with regular expressions.
|
33 | It can also be **embedded** and **extended**.
|
34 |
|
35 | # Rational
|
36 |
|
37 | Initially started to build a local **development environment** where static files are served and resources can be fetched from remote repositories, this **tool** is **versatile** and can support different scenarios :
|
38 | - A simple web server
|
39 | - A reverse proxy to an existing server
|
40 | - A server that aggregates several sources
|
41 | - ...
|
42 |
|
43 | By defining **an array of mappings**, one can decide how the server will process the requests. Each mapping associates a **matching** criterion defined with a
|
44 | [regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) to a **handler** that will answer the request.
|
45 |
|
46 | The configuration syntax favors **simplicity** without dropping flexibility.
|
47 |
|
48 | For instance, the definition of a server that **exposes files** of the current directory but **forbids access** to the directory `private` consists in :
|
49 |
|
50 | ```json
|
51 | {
|
52 | "port": 8080,
|
53 | "mappings": [{
|
54 | "match": "^/private/.*",
|
55 | "status": 403
|
56 | }, {
|
57 | "match": "^/(.*)",
|
58 | "file": "./$1"
|
59 | }]
|
60 | }
|
61 | ```
|
62 |
|
63 | ## More documentation
|
64 |
|
65 | Go to this [page](https://github.com/ArnaudBuchholz/reserve/tree/master/doc/README.md) to access articles about REserve.
|
66 |
|
67 | # What's New ?
|
68 |
|
69 | |Version|content|
|
70 | |---|---|
|
71 | |1.0.0|Initial version|
|
72 | |1.0.5|`watch` option in **custom** handler|
|
73 | |1.1.1|[`require('reserve/mock')`](#mocking)|
|
74 | ||[`colors`](https://www.npmjs.com/package/colors) and [`mime`](https://www.npmjs.com/package/mime) are no more dependencies|
|
75 | |1.1.2|Performance testing, `--silent`|
|
76 | ||`case-sensitive` option in **file** handler|
|
77 | |1.1.3|Changes default hostname to `undefined`|
|
78 | |1.1.4|Enables external handlers in `json` configuration through [require](https://nodejs.org/api/modules.html#modules_require_id)|
|
79 | |1.1.5|Fixes relative path use of external handlers in `json` configuration|
|
80 | |1.1.6|Improves response mocking (`flushHeaders()` & `headersSent`)|
|
81 | |1.1.7|Compatibility with Node.js >= 12.9|
|
82 | ||Improves response mocking|
|
83 | |1.2.0|Implements handlers' schema|
|
84 | ||Gives handlers access to a configuration interface|
|
85 | ||Prevents infinite loops during internal redirection (see `max-redirect`)|
|
86 | |1.2.1|Fixes coloring in command line usage|
|
87 | |1.3.0|Fixes infinite loop in the error handler|
|
88 | ||Adds experimental `use` handler for [express middleware functions](https://www.npmjs.com/search?q=keywords%3Aexpress%20keywords%3Amiddleware)|
|
89 | ||Makes the mapping `match` member optional|
|
90 | |1.4.0|More [documentation](https://github.com/ArnaudBuchholz/reserve/tree/master/doc/README.md) |
|
91 | ||Exposes simple body reader (`require('reserve').body`)|
|
92 | ||Adds `method` specification *(handlers & mappings)*|
|
93 | |1.5.0|`headers` option in **status** handler *(enables HTTP redirect)*|
|
94 | ||`ignore-if-not-found` option in **file** handler *(enables folder browsing with a separate handler)*|
|
95 | |1.6.0|Implements `$%1` and `$&1` substitution parameters *(see [Custom handlers](#custom-handlers))*|
|
96 | |1.6.1|Exposes `require('reserve').interpolate` *(see [Custom handlers](#custom-handlers))*|
|
97 |
|
98 | # Usage
|
99 |
|
100 | ## In a project
|
101 |
|
102 | * Install the package with `npm install reserve` *(you decide if you want to save it as development dependency or not)*
|
103 | * You may create a start script in `package.json` :
|
104 |
|
105 | ```json
|
106 | {
|
107 | "scripts": {
|
108 | "start": "reserve"
|
109 | }
|
110 | }
|
111 | ```
|
112 |
|
113 | * By default, it will look for a file named `reserve.json` in the current working directory
|
114 | * A configuration file name can be specified using `--config <file name>`, for instance :
|
115 |
|
116 | ```json
|
117 | {
|
118 | "scripts": {
|
119 | "start": "reserve",
|
120 | "start-dev": "reserve --config reserve-dev.json"
|
121 | }
|
122 | }
|
123 | ```
|
124 |
|
125 | ## Global
|
126 |
|
127 | * Install the package with `npm install reserve --global`
|
128 | * Run `reserve`
|
129 | * By default, it will look for a file named `reserve.json` in the current working directory
|
130 | * A configuration file name can be specified using `--config <file name>`
|
131 |
|
132 | **NOTE** : if [`process.send`](https://nodejs.org/api/process.html#process_process_send_message_sendhandle_options_callback) is defined, REserve will notify the parent process when the server is ready by sending the message `'ready'`.
|
133 |
|
134 | # Embedding
|
135 |
|
136 | It is possible to implement the server in any application using the `reserve/serve` module :
|
137 |
|
138 | ```javascript
|
139 | const path = require('path')
|
140 | const reserve = require('reserve/serve')
|
141 | reserve({
|
142 | port: 8080,
|
143 | mappings: [{
|
144 | match: /^\/(.*)/,
|
145 | file: path.join(__dirname, '$1')
|
146 | }]
|
147 | })
|
148 | .on('ready', ({ url }) => {
|
149 | console.log(`Server running at ${url}`)
|
150 | })
|
151 | ```
|
152 |
|
153 | The resulting object implements the [EventEmitter](https://nodejs.org/api/events.html) class and throws the following events with parameters :
|
154 |
|
155 | | Event | Parameter (object containing members) | Description |
|
156 | |---|---|---|
|
157 | | **ready** | `url` *(String, example : `'http://0.0.0.0:8080/'`)*| The server is listening and ready to receive requests, hostname is replaced with `0.0.0.0` when **unspecified**.
|
158 | | **incoming** | `method` *(String, example : `'GET'`)*, `url` *(String)*, `start` *(Date)* | New request received, these parameters are also transmitted to **error**, **redirecting** and **redirected** events |
|
159 | | **error** | `reason` *(Any)* | Error reason, contains **incoming** parameters if related to a request |
|
160 | | **redirecting** | `type` *(Handler type, example : `'status'`)*, `redirect` *(String or Number, example : `404`)* | Processing redirection to handler, gives handler type and redirection value. <br />*For instance, when a request will be served by the [file handler](#file), this event is generated once. But if the requested resource does not exist, the request will be redirected to the [status](#status) 404 triggering again this event.* |
|
161 | | **redirected** | `end` *(Date)*, `timeSpent` *(Number of ms)*, `statusCode` *(Number)* | Request is fully processed. `timeSpent` is evaluated by comparing `start` and `end` (i.e. not using high resolution timers) and provided for information only. |
|
162 |
|
163 | The package also gives access to the configuration reader :
|
164 |
|
165 | ```javascript
|
166 | const path = require('path')
|
167 | const { read } = require('reserve/configuration')
|
168 | const reserve = require('reserve/serve')
|
169 | read('reserve.json')
|
170 | .then(configuration => {
|
171 | reserve(configuration)
|
172 | .on('ready', ({ url }) => {
|
173 | console.log(`Server running at ${url}`)
|
174 | })
|
175 | })
|
176 | ```
|
177 |
|
178 | And a default log output *(verbose mode will dump all redirections)* :
|
179 |
|
180 | ```javascript
|
181 | const path = require('path')
|
182 | const { read } = require('reserve/configuration')
|
183 | const log = require('reserve/log')
|
184 | const reserve = require('reserve/serve')
|
185 | read('reserve.json')
|
186 | .then(configuration => {
|
187 | log(reserve(configuration), /*verbose: */ true)
|
188 | })
|
189 | ```
|
190 |
|
191 | NOTE: log is using [`colors`](https://www.npmjs.com/package/colors) **if installed**.
|
192 |
|
193 | # Configuration
|
194 |
|
195 | ## hostname *(optional)*
|
196 |
|
197 | Used to set the `host` parameter when calling http(s) server's [listen](https://nodejs.org/api/net.html#net_server_listen).
|
198 |
|
199 | Default is `undefined`.
|
200 |
|
201 | ## port *(optional)*
|
202 |
|
203 | Used to set the `port` parameter when calling http(s) server's [listen](https://nodejs.org/api/net.html#net_server_listen).
|
204 |
|
205 | Default is `5000`.
|
206 |
|
207 | ## max-redirect *(optional)*
|
208 |
|
209 | Limits the number of internal redirections. If the number of redirections goes beyond the parameter value, the request fails with error [`508`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/508).
|
210 |
|
211 | Default is `10`.
|
212 |
|
213 | ## ssl *(optional)*
|
214 |
|
215 | This object provides certificate information to build an https server. You might be interested by the article [An Express HTTPS server with a self-signed certificate](https://flaviocopes.com/express-https-self-signed-certificate/).
|
216 |
|
217 | The object must contain :
|
218 | * `cert` : a relative or absolute path to the certificate file
|
219 | * `key` : a relative or absolute path to the key file
|
220 |
|
221 | If relative, the configuration file directory or the current working directory (when embedding) is considered.
|
222 |
|
223 | ## handlers
|
224 |
|
225 | An object associating a handler prefix to a handler object.
|
226 | If the property value is a string, the handler is obtained using [require](https://nodejs.org/api/modules.html#modules_require_id).
|
227 |
|
228 | For instance : every mapping containing the `cache` property will be associated to the [REserve/cache](https://www.npmjs.com/package/reserve-cache) handler.
|
229 |
|
230 | ```json
|
231 | {
|
232 | "handlers": {
|
233 | "cache": "reserve-cache"
|
234 | }
|
235 | }
|
236 | ```
|
237 |
|
238 | **NOTE** : it is not possible to change the associations of the default prefixes (`custom`, `file`, `status`, `url`, `use`). **No error** will be thrown if a prefix collides with a predefined one.
|
239 |
|
240 | See [Custom handlers](#custom-handlers) for more information.
|
241 |
|
242 | ## mappings
|
243 |
|
244 | An array of mappings that is evaluated in the order of declaration.
|
245 | * Several mappings may apply to the same request
|
246 | * Evaluation stops when the request is **finalized** *(see the note below)*
|
247 | * When a handler triggers a redirection, the array of mappings is re-evaluated
|
248 |
|
249 | **NOTE** : REserve hooks the [`response.end`](https://nodejs.org/api/http.html#http_response_end_data_encoding_callback) API to detect when the response is finalized.
|
250 |
|
251 | Each mapping must contain :
|
252 | * `match` *(optional)* : a string (converted to a regular expression) or a regular expression that will be applied to the [request URL](https://nodejs.org/api/http.html#http_message_url), defaulted to `"(.*)"`
|
253 | * `method` *(optional)* : a comma separated string or an array of [HTTP verbs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) that is matched with the [request method](https://nodejs.org/api/http.html#http_message_method), defaulted to `undefined` *(meaning all methods are allowed)*.
|
254 | * the handler prefix (`custom`, `file`, `status`, `url`, `use` ...) which value may contain capturing groups *(see [Custom handlers](#custom-handlers))*
|
255 | * `cwd` *(optional)* : the current working directory to consider for relative path, defaulted to the configuration file directory or the current working directory (when embedding)
|
256 |
|
257 | **NOTE** : when using `custom` in a [JSON](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) file, since functions can't be used in this format, the expected value is a string referencing the relative or absolute module to load. If relative, the `cwd` member is considered.
|
258 |
|
259 | **NOTE** : each **handler may provide its own `method` parameter** depending on which verbs are implemented. The mapping's `method` value **cannot** allow a verb that is not implemented. As a consequence **an error is thrown** if the combination of handler and mapping `method` parameters leads to an empty list.
|
260 |
|
261 | For instance :
|
262 |
|
263 | * `reserve.json` :
|
264 |
|
265 | ```json
|
266 | {
|
267 | "port": 8080,
|
268 | "mappings": [{
|
269 | "custom": "./cors"
|
270 | }, {
|
271 | "match": "^/(.*)",
|
272 | "file": "./$1"
|
273 | }]
|
274 | }
|
275 | ```
|
276 |
|
277 | * `cors.js` :
|
278 |
|
279 | ```javascript
|
280 | module.exports = async (request, response) => response.setHeader('Access-Control-Allow-Origin', '*')
|
281 | ```
|
282 |
|
283 | ## extend
|
284 |
|
285 | *Only for JSON configuration*
|
286 |
|
287 | A relative or absolute path to another configuration file to extend.
|
288 | If relative, the current configuration file directory is considered.
|
289 |
|
290 | The current settings overwrite the ones coming from the extended configuration file.
|
291 |
|
292 | Extended `mappings` are imported at the end of the resulting array, making the current ones being evaluated first. This way, it is possible to override the extended mappings.
|
293 |
|
294 | # Handlers
|
295 |
|
296 | ## file
|
297 |
|
298 | Answers the request using **file system**.
|
299 |
|
300 | Example :
|
301 | ```json
|
302 | {
|
303 | "match": "^/(.*)",
|
304 | "file": "./$1"
|
305 | }
|
306 | ```
|
307 |
|
308 | * Only supports [GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET)
|
309 | * Capturing groups can be used as substitution parameters
|
310 | * Absolute or relative to the handler's `cwd` member *(see [mappings](#mappings))*
|
311 | * Incoming URL parameters are automatically stripped out to simplify the matching expression
|
312 | * Directory access is internally redirected to the inner `index.html` file *(if any)* or `404` status
|
313 | * File access returns `404` status if missing or can't be read
|
314 | * Mime type computation is based on [`mime`](https://www.npmjs.com/package/mime) **if installed**. Otherwise a limited subset of mime types is used:
|
315 |
|
316 | |Extension|mime type|
|
317 | |---|---|
|
318 | |bin|application/octet-stream|
|
319 | |css|text/css|
|
320 | |gif|image/gif|
|
321 | |html|text/html|
|
322 | |htm|text/html|
|
323 | |jpeg|image/jpeg|
|
324 | |jpg|image/jpeg|
|
325 | |js|application/javascript|
|
326 | |pdf|application/pdf|
|
327 | |png|image/png|
|
328 | |svg|image/svg+xml|
|
329 | |text|text/plain|
|
330 | |txt|text/plain|
|
331 | |xml|application/xml|
|
332 |
|
333 | | option | type | default | description |
|
334 | |---|---|---|---|
|
335 | | `case-sensitive` | Boolean | `false` | *(for Windows)* when `true`, the file path is tested case sensitively. Since it has an impact on **performances**, use carefully. |
|
336 | | `ignore-if-not-found` | Boolean | `false` | If the mapping does not resolve to a file or a folder, the handler does not end the request with status `404`. |
|
337 |
|
338 | ## url
|
339 |
|
340 | Answers the request by **forwarding** it to a different URL.
|
341 |
|
342 | Example :
|
343 | ```json
|
344 | {
|
345 | "match": "^/proxy/(https?)/(.*)",
|
346 | "url": "$1://$2",
|
347 | "unsecure-cookies": true
|
348 | }
|
349 | ```
|
350 |
|
351 | * Supports [all HTTP methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)
|
352 | * Capturing groups can be used as substitution parameters
|
353 | * Redirects to any URL (http or https)
|
354 |
|
355 | **NOTE** : It must redirect to an absolute URL
|
356 |
|
357 | | option | type | default | description |
|
358 | |---|---|---|---|
|
359 | | `unsecure-cookies` | Boolean | `false` | when `true`, the secured cookies are converted to unsecure ones. Hence, the browser will keep them even if not running on https |
|
360 |
|
361 | ## custom
|
362 |
|
363 | Enables 'simple' **custom** handlers.
|
364 |
|
365 | Examples :
|
366 | ```javascript
|
367 | {
|
368 | custom: async (request, response) => response.setHeader('Access-Control-Allow-Origin', '*')
|
369 | }
|
370 | ```
|
371 |
|
372 | Or using an external module :
|
373 |
|
374 | ```javascript
|
375 | {
|
376 | custom: './cors.js'
|
377 | }
|
378 | ```
|
379 |
|
380 | with `cors.js` :
|
381 | ```javascript
|
382 | module.exports = async (request, response) => response.setHeader('Access-Control-Allow-Origin', '*')
|
383 | ```
|
384 |
|
385 | External modules are loaded with Node.js [require](https://nodejs.org/api/modules.html#modules_require_id) API.
|
386 |
|
387 | `custom` must point to a [function](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Functions)
|
388 | * That takes at least two parameters : [`request`](https://nodejs.org/api/http.html#http_class_http_incomingmessage) and [`response`](https://nodejs.org/api/http.html#http_class_http_serverresponse)
|
389 | * Capturing groups' values are passed as additional parameters.
|
390 | * This function must return a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
|
391 | * If the promise is resolved to a value (i.e. not `undefined`), an internal redirection occurs i.e. the request is going over the mappings again (*infinite loops are now prevented, see `max-redirect`*).
|
392 | * If the `response` is not **finalized** after executing the function *(i.e. [`response.end`](https://nodejs.org/api/http.html#http_response_end_data_encoding_callback) was not called)*, the `request` is going over the remaining mappings
|
393 |
|
394 | | option | type | default | description |
|
395 | |---|---|---|---|
|
396 | | `watch` | Boolean | `false` | when `true` and using a local module *(does not work with `node_modules`)* the file's modified time is checked before executing the handler. When changed, the module is reloaded |
|
397 |
|
398 | ## status
|
399 |
|
400 | **Ends** the request with a given status.
|
401 |
|
402 | Example :
|
403 | ```json
|
404 | {
|
405 | "match": "^/private/.*",
|
406 | "status": 403
|
407 | }
|
408 | ```
|
409 |
|
410 | * Supports [all HTTP methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods)
|
411 | * Accepts only Numbers
|
412 | * Also used when an internal redirection to a Number occurs
|
413 | * Capturing groups can be used in the headers' values
|
414 | * End the response with the given status and, if defined, with a textual message :
|
415 |
|
416 | | status | message |
|
417 | |---|---|
|
418 | | 403 | Forbidden |
|
419 | | 404 | Not found |
|
420 | | 405 | Method Not Allowed |
|
421 | | 500 | Internal Server Error |
|
422 | | 501 | Not Implemented |
|
423 | | 508 | Loop Detected |
|
424 |
|
425 | | option | type | default | description |
|
426 | |---|---|---|---|
|
427 | | `headers` | Object | `{}` | Additional response headers (capturing groups can be used as substitution parameters in values) |
|
428 |
|
429 | ## use
|
430 |
|
431 | Enables the use of [express middleware functions](https://www.npmjs.com/search?q=keywords%3Aexpress%20keywords%3Amiddleware).
|
432 |
|
433 | **NOTE** : Supports only middleware functions accepting exactly three parameters (`request`, `response` and `next`) as described [here](http://expressjs.com/en/guide/writing-middleware.html).
|
434 |
|
435 | **NOTE** : This is an **experimental feature** that needs deeper testing.
|
436 |
|
437 | Example :
|
438 |
|
439 | ```json
|
440 | {
|
441 | "use": "express-session",
|
442 | "options" : {
|
443 | "secret": "keyboard cat",
|
444 | "resave": false,
|
445 | "saveUninitialized": true
|
446 | }
|
447 | }
|
448 | ```
|
449 |
|
450 | | option | type | default | description |
|
451 | |---|---|---|---|
|
452 | | `options` | Object | `{}` | Options passed to the middleware factory |
|
453 |
|
454 | ## Other handlers
|
455 |
|
456 | The following handlers can be installed separately and plugged through the `handlers` configuration property.
|
457 |
|
458 | | handler | description |
|
459 | |---|---|
|
460 | | [REserve/cache](https://www.npmjs.com/package/reserve-cache) | Caches string in memory |
|
461 | | [REserve/cmd](https://www.npmjs.com/package/reserve-cmd) | Wraps command line execution |
|
462 | | [REserve/fs](https://www.npmjs.com/package/reserve-fs) | Provides [fs](https://nodejs.org/api/fs.html) APIs to the browser |
|
463 |
|
464 | ## Custom handlers
|
465 |
|
466 | A custom handler object may define:
|
467 |
|
468 | * **schema** *(optional)* a mapping validation schema, see [below](#schema) for the proposed syntax
|
469 |
|
470 | * **method** *(optional)* a comma separated string or an array of [HTTP verbs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) that indicates which methods are implemented. When no value is provided, REserve considers that any verb is supported.
|
471 |
|
472 | * **validate** *(optional)* an [asynchronous](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) method that validates mapping definition, it will be called with two **parameters**:
|
473 | - **mapping** the mapping being validated
|
474 | - **configuration** the [configuration interface](#configuration-interface)
|
475 |
|
476 |
|
477 | * **redirect** *(mandatory)* an [asynchronous](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) method that will be called with an **object** exposing:
|
478 | - **configuration** the [configuration interface](#configuration-interface)
|
479 | - **mapping** the mapping being executed
|
480 | - **match** the regular expression [exec result](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec)
|
481 | - **redirect** the value associated with the handler prefix in the mapping. Capturing groups **are** substituted.
|
482 | - **request** Node.js' [http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage)
|
483 | - **response** Node.js' [http.ServerResponse](https://nodejs.org/api/http.html#http_class_http_serverresponse)
|
484 |
|
485 | ### Capturing groups and interpolation
|
486 |
|
487 | By default, the handler prefix is **interpolated**. Identified **placeholders are substituted** with values coming from the capturing groups of the matching regular expression.
|
488 |
|
489 | Three syntaxes are accepted for placeholders, `<index>` represents the capturing group index in the regular expression (1-based):
|
490 | * `$<index>` value is replaced **as-is**
|
491 | * `$&<index>` value is first **decoded** with [decodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI)
|
492 | * `$%<index>` value is first **decoded** with [decodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent)
|
493 |
|
494 | When writing an handler, it is possible to **reuse the mechanism** by importing the function `require('reserve').interpolate`. It accepts two parameters:
|
495 | * **match** the regular expression [exec result](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec)
|
496 | * **value** accepting multiple types :
|
497 | - `string` : value is interpolated and the result returned
|
498 | - `object` : property values are interpolated **recursively** and a new object is returned
|
499 | - otherwise the value is returned **as-is**
|
500 |
|
501 | ### Schema
|
502 |
|
503 | The schema syntax is designed to be short and self-explanatory. It is a dictionary mapping a property name to its specification.
|
504 |
|
505 | It can be either:
|
506 | * Simple type specification (for instance: `"string"`)
|
507 | * Multiple types specification (for instance `["function", "string"]`)
|
508 | * Complete specification: an object containing `type` (or `types`) and a `defaultValue` for optional properties.
|
509 |
|
510 | For instance, the following schema specification defines:
|
511 | * a **mandatory** `custom` property that must be either a `function` or a `string`
|
512 | * an **optional** `watch` boolean property which default value is `false`
|
513 |
|
514 | ```json
|
515 | {
|
516 | "schema": {
|
517 | "custom": ["function", "string"],
|
518 | "watch": {
|
519 | "type": "boolean",
|
520 | "defaultValue": false
|
521 | }
|
522 | }
|
523 | }
|
524 | ```
|
525 |
|
526 | If provided, the schema is applied on the mapping **before** the **validate** function.
|
527 |
|
528 | ### Configuration interface
|
529 |
|
530 | The configuration interface lets you access the dictionary of handlers (member `handlers`) as well as the array of existing mappings (member `mappings`).
|
531 |
|
532 | It is recommended to be extremely careful when manipulating the mappings' content, since you might break the logic of the server.
|
533 |
|
534 | It is possible to safely change the list of mapping using the [asynchronous](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) `setMappings` method. This API takes two parameters: the new list of mappings and the current request.
|
535 |
|
536 | The API will:
|
537 | * validate any new mapping *(relies on an internal detection mechanism based on symbols)*
|
538 | * wait for all pending requests to be completed before applying the new list
|
539 |
|
540 | # Helpers
|
541 |
|
542 | ## body
|
543 |
|
544 | Since version 1.4.0, the package offers a **basic** method to **read the request body**.
|
545 |
|
546 | ```javascript
|
547 | const { body } = require('reserve')
|
548 |
|
549 | async function customHandler (request, response) {
|
550 | const requestBody = JSON.parse(await body(request))
|
551 | /* ... */
|
552 | }
|
553 | ```
|
554 |
|
555 | # Mocking
|
556 |
|
557 | Since version 1.1.0, the package includes the helper `reserve/mock` to build tests. This method receives a configuration (like `reserve/serve`) and returns a promise resolving to an [EventEmitter](https://nodejs.org/api/events.html) augmented with a `request` method :
|
558 |
|
559 | ```javascript
|
560 | function request (method, url, headers = {}, body = '') {
|
561 | return Promise.resolve(mockedResponse)
|
562 | }
|
563 | ```
|
564 |
|
565 | Call the `request` method to simulate an incoming request, it returns a promise resolving to a mocked response exposing the following members :
|
566 |
|
567 | | Member | Type | Description |
|
568 | |---|---|---|
|
569 | | **headers** | Object | Response headers
|
570 | | **statusCode** | Number | Status code
|
571 | | **finished** | Boolean | `true`
|
572 | | **toString()** | String | Gives the response body
|
573 |
|
574 | Example :
|
575 |
|
576 | ```javascript
|
577 | require('reserve/mock')({
|
578 | port: 8080,
|
579 | mappings: [{
|
580 | match: /^\/(.*)/,
|
581 | file: path.join(__dirname, '$1')
|
582 | }]
|
583 | })
|
584 | .then(mocked => mocked.request('GET', '/'))
|
585 | .then(response => {
|
586 | assert(response.statusCode === 200)
|
587 | assert(response.toString() === '<html />')
|
588 | })
|
589 | ```
|
590 |
|
591 | You may provide mocked handlers *(based on their [actual implementation](https://github.com/ArnaudBuchholz/reserve/tree/master/handlers))*:
|
592 |
|
593 | ```javascript
|
594 | require('reserve/mock')({
|
595 | port: 8080,
|
596 | mappings: [{
|
597 | match: /^\/(.*)/,
|
598 | file: path.join(__dirname, '$1')
|
599 | }]
|
600 | }, {
|
601 | file: {
|
602 | redirect: async ({ request, mapping, redirect, response }) => {
|
603 | if (redirect === '/') {
|
604 | response.writeHead(201, {
|
605 | 'Content-Type': 'text/plain',
|
606 | 'Content-Length': 6
|
607 | })
|
608 | response.end('MOCKED')
|
609 | } else {
|
610 | return 500
|
611 | }
|
612 | }
|
613 | }
|
614 | })
|
615 | .then(mocked => mocked.request('GET', '/'))
|
616 | .then(response => {
|
617 | assert(response.statusCode === 201)
|
618 | assert(response.toString() === 'MOCKED')
|
619 | })
|
620 | ```
|