Restar
Web library for rest api, async/await supported, simplistic with zero dependencies.
Installation
npm i restar -S
Benefits
- respond elegantly
app;
- comprehensible middleware
app; app; app; /* only /hello set response time */// app.end('/hello', (req, res) => {// res.setHeader('X-Response-Time', `${Date.now() - req.startAt}ms`);// });
- error handling elegantly
app; app; /* catch errors with route*/// app.catch('/test', e => (req, res) => {// return e.message + '2' || 'an error';// });
- async/await supported
app; { return ;}
- mount static directory with route
const serveStatic = ;app;/*serve static with route*/// app.use('/doc', routeStatic('/doc'), serveStatic(path.join(__dirname, '../public', 'doc'))); { return { const tail = requrl1; if !tail resstatusCode = 302; res; res; else requrl = requrl; ; };}
Usage
const Restar = ;let app = ; // use a global pluginapp; // equal to res.json({ name: 'restar' }) in expressapp; // you can retrieve parameters by deconstructing// (req,res)-({query,body})-({param:assign(query,body)})app; app; { return ;} app;
Async handler
app.[get|post|put|head|delete|options|all]
(handler1,handler2...)
handler(req?:IncomingMessage,res?:ServerResponse) : void|string|json|Buffer|ReadStream
app; { return ;}
API
app.use((req,res,next?)=>{})
Like express
middleware
const serveStatic = ;app;
app.end((req,res,next?)=>{})
Like express
middleware, execute after route handling
app;
app.catch(e=>(req,res,next?)=>{})
Error handling
app;
Examples
Looking for more usages and examples
https://github.com/cooperhsiung/restar-examples
Boilerplate
Restar app boilerplate
https://github.com/cooperhsiung/restar-kit
Caveats
path-to-regex
is unsupported
-
any urls like http://localhost:3000/user/1 could be converted to http://localhost:3000/user?id=1
-
when existing massive routes, it will hurt the preformance with
path-to-regex
In view of the above, in most cases we may not need path-to-regex
in restful web application
License
MIT