You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hey guys was wondering, what is the best way to implement a RouteHandler like the one present in @hono/zod-openapi based on my function below createRoute, I am using hono-openapi for .lazy() and a couple other features
import{db}from'@/database';importtype{Table}from'drizzle-orm';import{getTableConfig}from'drizzle-orm/pg-core';importtype{Env,Handler,MiddlewareHandler,TypedResponse}from'hono';import{describeRoute,typeDescribeRouteOptions}from'hono-openapi';import{resolver,validator}from'hono-openapi/zod';import{z,typeAnyZodObject,typeZodTypeAny}from'zod';importtype{Require}from'./types';exportfunctionresolveParamRecords<TextendsTable>(table: T){constconfig=getTableConfig(table);consttype=z.string().uuid().transform(async(id,ctx)=>{// @ts-ignore: This and the below ignores are there due to it needing to be a generic.constresult=awaitdb.query[config.nameaskeyoftypeofschema].findFirst({where: {
id,},});if(!result){ctx.addIssue({code: z.ZodIssueCode.custom,message: 'Not found',});returnz.NEVER;}returnresultasT['$inferSelect'];}).openapi({description: `Identification for table \`${config.name}\``,});// TODO Replace this with Metadata in Zod V4type._def.model=config.name;returntype;}exportconstRequestMethod={GET: 'get',POST: 'post',PUT: 'put',PATCH: 'patch',DELETE: 'delete',}asconst;typeBodyContentHeader='application/json'|'multipart/form-data';constresponses={404: {content: {'application/json': {schema: resolver(z.object({message: z.string().openapi({example: 'Not found'}),}),),},},description: 'Record not found',},500: {content: {'application/json': {schema: resolver(z.object({message: z.string().openapi({example: 'Internal server error'}),}),),},},description: 'Internal server error',},}asconst;typeHook=Parameters<typeofvalidator>[2];constdefaultHook: Hook=(result,c)=>{if(!result.success){if(result.error.issues.find((issue)=>issue.code==='custom'&&issue.message==='Not found')){returnc.json({message: 'Not found',},404,);}returnc.json({message: 'Failed validation',errors: result.error.flatten().fieldErrors,},422,);}};exporttypeRouteInput<QueryextendsAnyZodObject,ParamsextendsAnyZodObject,HeadersextendsAnyZodObject,JsonextendsAnyZodObject,FormextendsAnyZodObject,ContentextendsPartial<Record<BodyContentHeader,{schema: AnyZodObject}>>={'application/json'?: {schema: Json};'multipart/form-data'?: {schema: Form};},>=Require<DescribeRouteOptions,'responses'>&{path: string;method: keyoftypeofRequestMethod;request?: {query?: Query;params?: Params;body?: {content: Content;};headers?: Headers;};};exporttypeRouteOutput<QueryextendsAnyZodObject,ParamsextendsAnyZodObject,HeadersextendsAnyZodObject,JsonextendsAnyZodObject,FormextendsAnyZodObject,ContentextendsPartial<Record<BodyContentHeader,{schema: AnyZodObject}>>,RextendsRouteInput<Query,Params,Headers,Json,Form,Content>=RouteInput<Query,Params,Headers,Json,Form,Content>,>={path: R['path'];method: (typeofRequestMethod)[keyoftypeofRequestMethod];request?: R['request'];validators: MiddlewareHandler[];description: DescribeRouteOptions;route: ReturnType<typeofdescribeRoute>;};exportfunctioncreateRoute<QueryextendsAnyZodObject=AnyZodObject,ParamsextendsAnyZodObject=AnyZodObject,HeadersextendsAnyZodObject=AnyZodObject,JsonextendsAnyZodObject=AnyZodObject,FormextendsAnyZodObject=AnyZodObject,ContentextendsPartial<Record<BodyContentHeader,{schema: AnyZodObject}>>={'application/json'?: {schema: Json};'multipart/form-data'?: {schema: Form};},RextendsRouteInput<Query,Params,Headers,Json,Form,Content>=RouteInput<Query,Params,Headers,Json,Form,Content>,>({ path, method, request, ...description}: R): RouteOutput<Query,Params,Headers,Json,Form,Content,R>{constvalidators: MiddlewareHandler[]=[];if(request?.query){validators.push(validator('query',request.query,defaultHook));}if(request?.headers){validators.push(validator('header',request.headers,defaultHook));}if(request?.params){validators.push(validator('param',request.params,defaultHook));// Has model so can 404if(Object.values(request.params.shape).findIndex((value)=>!!(valueasZodTypeAny)?._def.model)!==-1){description.responses[404]=responses[404];}}constcontent=request?.body?.content;if(content?.['application/json']){validators.push(validator('json',content['application/json'].schema,defaultHook));}if(content?.['multipart/form-data']){validators.push(validator('json',content['multipart/form-data'].schema,defaultHook));}description.responses[500]=responses[500];return{
path,method: RequestMethod[method],
request,
validators,
description,route: describeRoute(description),};}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hey guys was wondering, what is the best way to implement a
RouteHandlerlike the one present in@hono/zod-openapibased on my function belowcreateRoute, I am usinghono-openapifor.lazy()and a couple other featuresBeta Was this translation helpful? Give feedback.
All reactions