Egg.js + Joi for interface parameter verification

Joi is a powerful JavaScript data validation library for validating and converting data formats. Whether in back-end or front-end development, data validation is a critical step to ensure data integrity and consistency. Joi provides a concise and flexible way to define validation rules to ensure that input data meets expected requirements.
This article will introduce how to use Joifor data validation and Egg.jshow to integrate Joifor interface parameter validation.

Egg.js + Joi

1. Introduction to Joi

Joi is a Node.js module for validating the structure and values ​​of JavaScript objects. It provides a fluent API to easily define data validation rules. Whether validating user input, API requests, or configuration files, Joi helps developers ensure the legitimacy of their data.

2. Install Joi

Before starting, make sure your project has Node.js installed. To use Joi in your project, you can install it via npm or pnpm:

npm install joi
# 或者
pnpm add joi

3. Basic usage of Joi

Here is an example of basic data validation using Joi:

const Joi = require('joi');

// 定义验证规则
const schema = Joi.object({
    
    
  username: Joi.string().alphanum().min(3).max(30).required(),
  email: Joi.string().email().required(),
  age: Joi.number().integer().min(18).max(99),
});

// 要验证的数据
const data = {
    
    
  username: 'john_doe',
  email: '[email protected]',
  age: 25,
};

// 进行验证
const result = schema.validate(data);

if (result.error) {
    
    
  console.error(result.error.details);
} else {
    
    
  console.log('数据验证通过');
}

In the above example, we first define a validation rule schema, and then create a data object data to be validated. By calling the schema.validate(data) method, we can get the validation results. If the data conforms to the rules, result.error will be null, otherwise it will contain a detailed list of error messages.

4. Joi advanced usage

Joi can not only validate basic data types, but also handle complex data structures such as nested objects, arrays, and asynchronous validation. Here are some advanced usage examples:

  1. Nested object validation:
const addressSchema = Joi.object({
    
    
  street: Joi.string().required(),
  city: Joi.string().required(),
  zipCode: Joi.string().pattern(/^\d{5}$/).required(),
});

const personSchema = Joi.object({
    
    
  name: Joi.string().required(),
  age: Joi.number().integer().min(0).required(),
  address: addressSchema,
});

const personData = {
    
    
  name: 'Alice',
  age: 30,
  address: {
    
    
    street: '123 Main St',
    city: 'Exampleville',
    zipCode: '12345',
  },
};

const personResult = personSchema.validate(personData);
  1. Array validation:
const itemSchema = Joi.object({
    
    
  name: Joi.string().required(),
  price: Joi.number().min(0).required(),
});

const cartSchema = Joi.array().items(itemSchema).min(1);

const cartData = [
  {
    
     name: 'Item 1', price: 10 },
  {
    
     name: 'Item 2', price: 20 },
];

const cartResult = cartSchema.validate(cartData);
  1. Asynchronous validation
const asyncSchema = Joi.object({
    
    
  username: Joi.string().alphanum().min(3).max(30).required(),
  // 异步验证函数,返回 Promise
  isUsernameAvailable: Joi.function().async().required(),
});

const asyncData = {
    
    
  username: 'new_user',
  isUsernameAvailable: async (username) => {
    
    
    // 在实际应用中,可以查询数据库或调用 API 来检查用户名是否可用
    const isAvailable = await checkUsernameAvailability(username);
    if (!isAvailable) {
    
    
      throw new Error('Username is not available');
    }
  },
};

const asyncResult = await asyncSchema.validateAsync(asyncData);

5. Egg.js integrates Joi

Data validation is a vital part of web application development, helping to ensure the legality and integrity of input data. In the Egg.js framework, you can easily perform data validation with the help of the Joi library. This article will introduce how to use Joi for data validation in the Egg.js project to ensure that the received data meets the expected format and requirements.

First, app/controllercreate a new controller file in the controller directory, for example user.js:

// app/controller/user.js

const Controller = require('egg').Controller;
const Joi = require('joi');

class UserController extends Controller {
    
    
  async create() {
    
    
    const {
    
     ctx } = this;
    
    // 定义验证规则
    const schema = Joi.object({
    
    
      username: Joi.string().alphanum().min(3).max(30).required(),
      email: Joi.string().email().required(),
      age: Joi.number().integer().min(18).max(99),
    });

    // 获取请求体数据
    const requestBody = ctx.request.body;

    // 进行数据验证
    const validationResult = schema.validate(requestBody);

    if (validationResult.error) {
    
    
      ctx.status = 400;
      ctx.body = {
    
    
        message: '数据验证失败',
        details: validationResult.error.details,
      };
      return;
    }

    // 数据验证通过,继续处理业务逻辑
    // ...
  }
}

module.exports = UserController;

In the above example, we first imported the Controller class of Joi and Egg.js. In the create method, we define the validation rule schema, then obtain the request body data requestBody and perform data validation. If the verification fails, we return a response containing error information; if the verification passes, we can continue processing the business logic.

6. Summary

Joi is a powerful and easy-to-use data validation library for a variety of JavaScript applications. By defining clear validation rules, the legitimacy of input data can be effectively ensured, thereby improving data quality and application stability. Whether it's simple data validation or complex data structures, Joi can meet your needs and make data validation simpler and more efficient.
By integrating Joi data validation in your Egg.js project, you can ensure the legitimacy of your input data and reduce potential errors and security risks. Joi provides concise and flexible validation rule definitions to help you easily cope with different types of data validation needs.

Reference documentation: https://joi.dev/


Welcome to: Tianwen Blog

Guess you like

Origin blog.csdn.net/tiven_/article/details/132407365