简体   繁体   中英

How to use Nuxt 3 api middleware just for one endpoint?

code here: https://stackblitz.com/edit/github-jegnhv?file=server/api/users/index.post.js

I want to use validateUserSchema as middleware only for endpoint /api/users with POST method.

I still haven't found what I wanted, so this is my solution with decorator:

import { BaseSchema } from "yup";
import { sendError, H3Error, CompatibilityEvent } from "h3";

const validateBody = (schema: BaseSchema) => {
  return (
    _target: any,
    _propertyName: string,
    descriptor: TypedPropertyDescriptor<(...args: any[]) => void>
  ) => {
    const method = descriptor.value!;
    descriptor.value = async function (...args) {
      try {
        const body = await useBody(args[0].req);
        if (!body) {
          throw new H3Error("No body found");
        }
        await schema.validate(body);
      } catch (error) {
        sendError(
          args[0],
          new H3Error("Validation error")
        );
      }
      return method.apply(this, args);
    };
  };
};

class CreateUser {
  @validateBody(userSchema)
  static async handler(event: CompatibilityEvent) {
    return await useBody(event.req);
  }
}

export default defineEventHandler(CreateUser.handler);

well, you can make it a server middleware by putting it in server/middleware/users.post.ts(js) file. There you can extend your request context by edidting e.context.your_name Finally, you can return an error inside your handler in server/api/user.post.ts(js) and handle it on the client. Remember that in order to achieve both good security and UX you need to make both server and client-side form validation. On the client you can use :invalid css selector or pattern attribute. check out the MDN docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM