worktop是面向CloudflareWorkers的下一代Web框架。
特性:
超轻量级一流的TypeScript支持自定义中间件支持用于点菜功能的组织良好的子模块*包括支持模式定义的路由器熟悉的请求-响应处理程序API支持async/await处理程序完全treeshakableimport{Router}from'worktop';import*asCachefrom'worktop/cache';import{uidastoUID}from'worktop/utils';import{read,write}from'worktop/kv';importtype{KV}from'worktop/kv';declarevarDATA:KV.Namespace;interfaceMessage{id:string;text:string;//...}//InitializeconstAPI=newRouter();API.add('GET','/messages/:id',async(req,res)=>{//Pre-parsed`req.params`objectconstkey=`messages::${req.params.id}`;//AssumesJSON(canoverride)constmessage=awaitread<Message>(DATA,key);//Alterresponseheadersdirectlyres.setHeader('Cache-Control','public,max-age=60');//Smart`res.send()`helper//~>automaticallystringifiesJSONobjects//~>auto-sets`Content-Type`&`Content-Length`headersres.send(200,message);});API.add('POST','/messages',async(req,res)=>{try{//Smart`req.body`helper//~>parsesJSONheaderasJSON//~>parsesform-likeheaderasFormData,...etcvarinput=awaitreq.body<Message>();}catch(err){returnres.send(400,'Errorparsingrequestbody');}if(!input||!input.text.trim()){returnres.send(422,{text:'required'});}constvalue:Message={id:toUID(16),text:input.text.trim(),//...};//AssumesJSON(canoverride)constkey=`messages::${value.id}`;constsuccess=awaitwrite<Message>(DATA,key,value);//^boolean//Aliasfor`event.waitUntil`//~>queuesbackgroundtask(doesNOTdelayresponse)req.extend(fetch('https://.../logs',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({success,value})}));if(success)res.send(201,value);elseres.send(500,'Errorcreatingrecord');});API.add('GET','/alive',(req,res)=>{res.end('OK');//Node.js-like`res.end`});//Attach"fetch"eventhandler//~>use`Cache`forrequest-matching,whenpermitted//~>storeResponsein`Cache`,whenpermittedCache.listen(API.run);
评论