ADONISJS:验证HTTP请求之外的一些数据

ADONISJS: validate some data outside the HTTP request in

这是我的验证器class

 import { schema, rules } from "@ioc:Adonis/Core/Validator";
    import { HttpContextContract } from "@ioc:Adonis/Core/HttpContext";
    
    export default class CreateUserValidator {
      constructor(protected ctx: HttpContextContract) {}
    
      schema = schema.create({
        lat: schema.string({}, [
          rules.regex(/^[-]?(([0-8]?[0-9])\.(\d+))|(90(\.0+)?)$/),
        ]),
    
        lng: schema.string({}, [
          rules.regex(/^[-]?((((1[0-7][0-9])|([0-9]?[0-9]))\.(\d+))|180(\.0+)?)$/),
        ]),
        radius: schema.number(),
        distance: schema.number(),
      });
    
      public messages = {};
    }

这是我的控制器

import { validator } from '@ioc:Adonis/Core/Validator'
import CreateUser from 'App/Validators/CreateUserValidator'

public async station({
    request,
    response,
  }: HttpContextContract) {
    let inputs: any = await EncyptionManager.decrypt(request.body().inputs);
    inputs = JSON.parse(inputs);

    await validator.validate(
      new CreateUser({
        lat: ainputs.lat,
        long: ainputs.lat,
        radius: ainputs.radius,
        distance: ainputs.distance,
      })
    );
    
    console.log(inputs)

简单地说,我想在 HTTP 请求之外使用验证器 class 来验证纬度、经度、半径和距离。

因为验证器构造函数正在请求 ctx 并且我们正在传递数据 我们必须更新验证器构造函数并删除对 ctx 的依赖并接受数据

现在我的验证器接受数据

import { schema, rules } from "@ioc:Adonis/Core/Validator";
    import { HttpContextContract } from "@ioc:Adonis/Core/HttpContext";
    
    export default class CreateUserValidator {
      constructor() {}
    
      schema = schema.create({
        lat: schema.string({}, [
          rules.regex(/^[-]?(([0-8]?[0-9])\.(\d+))|(90(\.0+)?)$/),
        ]),
    
        lng: schema.string({}, [
          rules.regex(/^[-]?((((1[0-7][0-9])|([0-9]?[0-9]))\.(\d+))|180(\.0+)?)$/),
        ]),
        radius: schema.number(),
        distance: schema.number(),
      });
    
      public messages = {};
    }