@luukgoossen/elysia-procedures
Version:
tRPC style procedures and actions with TypeBox validation
3 lines (2 loc) • 2.4 kB
JavaScript
import{Value as J}from"@sinclair/typebox/value";import{Type as R}from"@sinclair/typebox";var L=(z)=>z.replace(/(?:^\w|[A-Z]|\b\w)/g,(D,E)=>E===0?D.toLowerCase():D.toUpperCase()).replace(/\s+/g,""),I=(z,D)=>R.Object({...D.properties,...z?z.properties:{}},{additionalProperties:!1});import{record as G}from"@elysiajs/opentelemetry";class M{_state;constructor(z){this._state=z}_apply=(z)=>{return new M({...this._state,...z})};params=(z)=>{let D=I(this._state.params,z);return this._apply({params:D})};query=(z)=>{let D=I(this._state.query,z);return this._apply({query:D})};body=(z)=>{let D=I(this._state.body,z);return this._apply({body:D})};output=(z)=>this._apply({output:z});build=(z)=>{return new N({handler:z,...this._state})}}class N{_handler;_middlewares;name;details;params;query;body;output;constructor(z){this._handler=z.handler,this._middlewares=z.middlewares,this.name=z.name,this.details=z.details,this.params=z.params,this.query=z.query,this.body=z.body,this.output=z.output}get docs(){return{params:this.params,query:this.query,body:this.body,response:this.output,detail:{summary:this.name,operationId:L(this.name),...this.details}}}handle=async(z)=>G(`Action: ${this.name}`,{attributes:{type:"handle",action:this.name}},async()=>{let{params:D,query:E,body:F,...H}=z;return await this._execute(H,{params:D,query:E,body:F})});run=async(z,D)=>G(`Action: ${this.name}`,{attributes:{type:"run",action:this.name}},async()=>{let{params:E,query:F,body:H}=D;await G("Validate Inputs",{attributes:{type:"input",action:this.name}},async()=>{if(this.params)E=this.params?J.Parse(this.params,D.params):D.params;if(this.query)F=this.query?J.Parse(this.query,D.query):D.query;if(this.body)H=this.body?J.Parse(this.body,D.body):D.body});let K=await this._execute(z,{params:E,query:F,body:H});if(!this.output)return K;let O=this.output;return G("Validate Output",{attributes:{type:"output",action:this.name}},()=>J.Parse(O,K))});_execute=async(z,D)=>{for(let E of this._middlewares)await G(`Middleware: ${E.name}`,{attributes:{type:"middleware",action:this.name}},async()=>{let F=await E.execute({params:D.params,query:D.query,body:D.body,ctx:z});if(F)z={...z,...F}});return await G("Main Handler",{attributes:{type:"handler",action:this.name}},async()=>{return await this._handler({params:D.params,query:D.query,body:D.body,ctx:z})})}}export{M as ActionBuilder,N as Action};
export{I as b,M as c};