0.0.33 • Published 6 years ago
@iljucha/server v0.0.33
Server
Im tired of the (req, res, next)-middlewares.\ So I created another way of creating middlewares.
Usage
import { Server } from "@iljucha/server"
// create server and listen to port 3000
const app = new Server(3000)
// example for body-parsing
// incomingMessage is also known as "req", "request" and so on
function _body(incomingMessage){
return new Promise((resolve, reject) => {
let body = []
incomingMessage.on("data", chunk => body.push(chunk) )
incomingMessage.on("end", () => resolve(Buffer.concat(body).toString()))
incomingMessage.on("error", error => reject(error))
})
}
// example middleware for simple ip-filering
function ipfilter(...ips) {
return ctx => {
if ([...ips].includes(ctx.ip)) {
ctx.status(403).end()
}
}
}
// true async, also nice middleware to slow down every connection
function slowDown(msec) {
return ctx => new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
}, msec)
})
}
// you just blocked every connection from you
app.use(/[\S\s]*/, ipfilter("127.0.0.1"))
// nice, now every connection is slow as *firetruck*
app.use(/[\S\s]*/, slowDown(5000))
// create middleware for route "/4", fetch request body
app.use("/4", async ctx => ctx.set("body", await _body(ctx.incomingMessage)))
// very simple "hello world" - route
app.get("/", () => "hello world")
// synchronous return of requested method
app.get("/2", ctx => ctx.method)
// async route, fetch body
app.post("/3", async ctx => {
let body = await _body(ctx.incomingMessage)
console.log(body)
return "thank you"
})
// sent request-body back to the client
app.post("/4", async ctx => ctx.get("body"))
app.get("/user/:alias", async ctx => {
// ctx.get("_params")["alias"]
return "Welcome, " + ctx.params.alias
})0.0.33
6 years ago
0.0.32
6 years ago
0.0.31
6 years ago
0.0.30
6 years ago
0.0.29
6 years ago
0.0.26
6 years ago
0.0.27
6 years ago
0.0.28
6 years ago
0.0.25
6 years ago
0.0.23
6 years ago
0.0.24
6 years ago
0.0.21
6 years ago
0.0.22
6 years ago
0.0.20
6 years ago
0.0.17
6 years ago
0.0.18
6 years ago
0.0.19
6 years ago
0.0.16
6 years ago
0.0.14
6 years ago
0.0.15
6 years ago
0.0.13
6 years ago
0.0.12
6 years ago
0.0.11
6 years ago
0.0.10
6 years ago
0.0.9
6 years ago
0.0.8
6 years ago
0.0.6
6 years ago
0.0.5
6 years ago
0.0.4
6 years ago
0.0.3
6 years ago
0.0.2
6 years ago
0.0.1
6 years ago