Giter Site home page Giter Site logo

egg-joi's People

Contributors

dependabot[bot] avatar liuxiaodong avatar skyitachi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

egg-joi's Issues

是否可以添加对 Param 和 query 对象的验证?

下面是 Express 的实现,供参考:

export default function(validations, options = {
  // when true, allows object to contain unknown keys which are ignored. Defaults to false.
  allowUnknown: true,
  // allowUnknown: false,
  // stripUnknown: true,
  // when true, stops validation on the first error, otherwise returns all the errors found. Defaults to true
  abortEarly: true,
}) {
  // When stripUnknown is true, Joi will validate every parameter in req.params, req.body, req.query.
  // If false, Joi will only validate parameters specified in the given validation object and pass any others directly through.
  function validate(req, res, next) {
    if (!validations || !validations.isJoi) {
      return next(new Error('Must be a joi object.'))
    }
    // Get all of our req data items
    const body = req.body
    const params = req.params // RESTful API 参数
    const query = req.query
    let items = {}
    copyObject(params, items, null, null)
    copyObject(query, items, null, null)
    copyObject(body, items, null, null)

    try {
      Joi.validate(items, validations, options, function(err, value) {
        if (err) {
          console.log(items);
          next(err)
        } else {
          req.items = value
          next()
        }
      })
    } catch (err) {
      next(err)
    }

  }

  return validate
}

/**
 * 
 * 
 * @param {Object} from 
 * @param {Object} to 
 * @param {Object} validations list of validation keys.
 * @param {Boolean} decode 
 */
function copyObject(from, to, validations, decode) {
  if (from) {
    for (var key in from) {
      try {
        to[key] = (decode && typeof(from[key]) === 'string') ? decodeURIComponent(from[key]) : from[key]
      } catch (err) {
        to[key] = from[key]
      }
    }
  }
}

去掉 validate 同时返回 error 和 value

error 的获取应该直接try catch。而不是通过返回。

目前这样,下面这种偷懒技巧就不太好用了。

const { phone, password } = ctx.validate...

// 这样会不会很奇怪
const { value: { phone, password }} = ctx.validate...

需要支持自定义错误 .error()

目前Joi schema中如果使用了 .error(), 代码报错

例如:

login: Joi.object().keys({
      mobile: Joi.string().regex(/^1\d{10}$/).label('手机号码')
        .error(new Error('手机号码输入不正确')),
    }),

需要对.error()返回的结果进行处理
"Error: 手机号码输入不正确"

参数类型不会自动转换

如果以字符串的形式提交一个期望是number或者date类型的属性。通过验证后,joi会把数据类型转换成number或者date。 但是在这里依然是string类型

support typescript

I just write index.d.ts for egg-joi, dynamic validator interface support can use egg-ts-helper, just like egg-sequelize app/model directory. My approach as follow:

// egg-joi
// index.d.ts

import * as Joi from 'joi';

declare module 'egg' {
  interface Application {
    Joi: typeof Joi;
  }

  interface Context {
    validate<T>(schema: Joi.Schema, data: T, opt?: Joi.ValidationOptions, autoThrow?: boolean):  Joi.ValidationResult<T> | any;
  }
}

// in application
// tshelper.js

module.exports = {
  watchDirs: {
    validator: {
      directory: 'app/validator', // files directory.
      // pattern: '**/*.(ts|js)', // glob pattern, default is **/*.(ts|js). it doesn't need to configure normally.
      // ignore: '', // ignore glob pattern, default to empty.
      generator: 'auto', // generator name, eg: class、auto、function、object
      interface: 'IValidator',  // interface name
      declareTo: 'Application.validator', // declare to this interface
      // watch: true, // whether need to watch files
      // caseStyle: 'upper', // caseStyle for loader
      // interfaceHandle: val => `ReturnType<typeof ${val}>`, // interfaceHandle
      // trigger: ['add', 'unlink'], // recreate d.ts when receive these events, all events: ['add', 'unlink', 'change']
    }
  }
}

// app/validator/api.ts

import { Application } from 'egg';

export default (app: Application) => {
  const Joi = app.Joi;
  return {
    dateRange: Joi.object().keys({
      begin: Joi.string().required(),
      end: [ Joi.string(), Joi.number() ],
    }),
  };
};

// generated file

// This file is created by [email protected]
// Do not modify this file!!!!!!!!!

import 'egg';
type AutoInstanceType<T, U = T extends (...args: any[]) => any ? ReturnType<T> : T> = U extends { new (...args: any[]): any } ? InstanceType<U> : U;
import ExportApi from '../../../app/validator/api';

declare module 'egg' {
  interface Application {
    validator: IValidator;
  }

  interface IValidator {
    api: AutoInstanceType<typeof ExportApi>;
  }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.