0.0.15 • Published 2 years ago
restfun v0.0.15
restfun
To run minimal and fast rest api on the edges.
Install
pnpm i restfun
bun add restfunUsage
Node.js
Hello word with restfun:
import restfun from 'restfun'
const server = restfun()
server.get('/', (req, res) => {
res.html('Hello world')
})
server.listen(3001)APIs
restfun
Syntax
restfun()
restfun(Object options)Parameters
options optional
cors: object, headers for cors, default to{}noDelay: bolean, default totruekeepAlive: bolean, default tofalsemaxHeaderSize: number, default to16384headersTimeout: number, default to60000requestTimeout: number, default to300000
Regarding cors, by default, restfun enalbe CORS by auto adding the following headers:
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: authorization, token, x-token, apikey, x-api-keyDeveloper can modify, or add more via cors options, for example:
import restfun from 'restfun'
export const server = restfun({
cors: {
'Access-Control-Allow-Origin': 'https://myownfrontend.com', // overwrite
'Access-Control-Allow-Credentials': 'true'
}
})For other options, refer this link.
Return
Return a restfun instance with the following methods:
listen(port, host, callback): start listening at the specified portget(pattern, handler): routes GET request to the specified patternpost(pattern, handler): routes POST request to the specified patternput(pattern, handler): routes PUT request to the specified patterndelete(pattern, handler): routes DELETE request to the specified patternroute(METHOD, pattern, handler: another way to add router using any HTTP methodsuse(handler): insert a handler in the middle of request/response processing, before the router handlersnotFound(handler): add handler to deal with 404 erroronError(handler): add handler to deal with other errors
patterns
This lib only support simple pattern, e.g,:
/:category/:slug/profile/:userid//accounts/:userid/settings/search/
handler
A function that accepts an IncomingMessage (a.k.a req) and a ServerResponse (a.k.a res).
Along with what are inherited from their prototype, restfun adds the following properties and methods to req/res:
req.ipreq.paramsreq.queryreq.bodyreq.getHeader()res.type()res.status()res.json()res.html()res.send()
Benchmark
autocannon -c 100 -w 4 -d 20 http://0.0.0.0:3001
- Intel® Core™ i7-10510U CPU @ 1.80GHz × 8
- RAM DDR4 2667 MT/s 16GB
- Node.js v18.12.1 on Debian 11.6
Test
git clone https://github.com/ndaidong/restfun.git
cd restfun
pnpm i
pnpm testLicense
The MIT License (MIT)