0.0.33 • Published 5 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
5 years ago
0.0.32
5 years ago
0.0.31
5 years ago
0.0.30
5 years ago
0.0.29
5 years ago
0.0.26
5 years ago
0.0.27
5 years ago
0.0.28
5 years ago
0.0.25
5 years ago
0.0.23
5 years ago
0.0.24
5 years ago
0.0.21
5 years ago
0.0.22
5 years ago
0.0.20
5 years ago
0.0.17
5 years ago
0.0.18
5 years ago
0.0.19
5 years ago
0.0.16
5 years ago
0.0.14
5 years ago
0.0.15
5 years ago
0.0.13
5 years ago
0.0.12
5 years ago
0.0.11
5 years ago
0.0.10
5 years ago
0.0.9
5 years ago
0.0.8
5 years ago
0.0.6
5 years ago
0.0.5
5 years ago
0.0.4
5 years ago
0.0.3
5 years ago
0.0.2
5 years ago
0.0.1
5 years ago