All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ph.com.nightowlstudios.resource.ValidationHandler Maven / Gradle / Ivy

There is a newer version: 6.21.1
Show newest version
package ph.com.nightowlstudios.resource;

/**
 * @author Joseph Harvey Angeles - @yev
 * @since 9/12/20
 */

import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;

/**
 * @author Joseph Harvey Angeles - @yev
 * @since 7/6/20
 */
public class ValidationHandler {

  public static Handler create(String... requiredParams) {
    return ctx -> {
      JsonObject body = ctx.getBodyAsJson();
      for (String param : requiredParams) {
        if (!body.containsKey(param)) {
          ctx.fail(HttpResponseStatus.BAD_REQUEST.code());
          ctx.response().setStatusCode(HttpResponseStatus.BAD_REQUEST.code()).end("Missing required parameter");
          return;
        }
      }
      ctx.next();
    };
  }

  public static Handler create(Validator validator) {
    return ctx -> {
      JsonObject body = ctx.getBodyAsJson();
      if (!validator.predicate().test(body)) {
        ctx.fail(HttpResponseStatus.PRECONDITION_FAILED.code());
        ctx.response().setStatusCode(HttpResponseStatus.PRECONDITION_FAILED.code()).end(validator.errorMessage());
        return;
      }
      ctx.next();
    };
  }
}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy