-
Notifications
You must be signed in to change notification settings - Fork 91
Creating middleware
Local-web-server uses Koa
as its middleware engine so first I recommend reading the Koa guide to writing middleware.
This is the minimum code to create a middleware module. A middleware module should export a function which returns a class extending MiddlewareBase
(a superclass supplied by ws
). The only required method is middleware
which is passed the active ws
configuration and must return a Koa middleware function.
This example sets the response body to 'Hello'
. Save it to a file named mw-example.js
.
module.exports = MiddlewareBase => class Example extends MiddlewareBase {
middleware (options) {
return (ctx, next) => {
ctx.response.body = 'Hello'
}
}
}
Launch your stack with the following command. By setting --stack
you override the built-in stack with the middleware supplied.
$ ws --stack mw-example.js
Serving at http://mbp.local:8100, http://127.0.0.1:8100, http://192.168.0.100:8100
Test you get the expected response.
$ curl http://127.0.0.1:8100
Hello
You can parameterise middleware by adding a optionDefinitions
method which should return one or more option definitions
. This example defines an option called message
which will be a string.
module.exports = MiddlewareBase => class Example extends MiddlewareBase {
optionDefinitions () {
return [
{ name: 'message', type: String, description: 'A message to print.'}
]
}
middleware (options) {
return (ctx, next) => {
ctx.response.body = 'Hello'
}
}
}
If you view the ws
usage guide you will now see your middleware and middleware options listed.
$ ws --stack mw-example.js --help