Skip to content

Commit

Permalink
refactor(app/decorator/validator): improve typing for zod validator
Browse files Browse the repository at this point in the history
  • Loading branch information
ikr4-m committed Feb 26, 2024
1 parent f0714d9 commit 1da1a87
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
9 changes: 7 additions & 2 deletions src/App/Decorator/Validator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,15 @@ import { z } from "zod";
import { MetadataValidatorConstant } from "App/Types/ControllerConstant.js";
import type Controller from "Controller/Controller.js";

type ZodData<V> = { [VK in keyof V]: any };

/**
* Set the path for route function.
* Validate data for route.
*
* @param method - Target of request
* @param data - Data to validate
*/
export default function validator<T extends {}>(method: keyof ValidationTargets, data: T): Function {
export default function validator<T extends {}>(method: keyof ValidationTargets, data: ZodData<T>): Function {
return function decorate(target: Controller, propKey: string, descriptor: PropertyDescriptor): void {
const targetFunc = descriptor.value as Function;
Reflect.defineMetadata(
Expand Down
8 changes: 2 additions & 6 deletions src/Controller/HelloController.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import type { ZodString } from "zod";
import { z } from "zod";
import httpRoute from "App/Decorator/HttpRoute.js";
import validator from "App/Decorator/Validator.js";
import type { DefaultHonoContext, HonoInputContext } from "App/Types/ControllerTypes.js";
import Controller from "./Controller.js";

type HelloValidator = {
message: ZodString | string;
message: string;
};

export default class HelloController extends Controller {
Expand All @@ -15,15 +14,12 @@ export default class HelloController extends Controller {
return c.text("Say hello world!");
}

/**
* TODO [2024-02-26]: Set In/Out Typing for Validator whatever it takes.
*/
@httpRoute("post", "/api")
@validator<HelloValidator>("json", {
message: z.string()
})
public helloApi(c: HonoInputContext<HelloValidator>): Response {
const { message } = c.req.valid("json");
return c.json(`Message: ${message as string}`);
return c.json(`Message: ${message}`);
}
}

0 comments on commit 1da1a87

Please sign in to comment.