elersong / fireorm24

ORM for Firebase Firestore 🔥 updated for 2024
MIT License
1 stars 0 forks source link

Implement Validate Decorator for Model Validation #23

Open elersong opened 3 months ago

elersong commented 3 months ago

Description

Fireorm supports validation by leveraging class-validator. The current implementation requires validation to be manually checked in each repository function. To improve code maintainability and readability, a Validate decorator should be created to handle this validation automatically.

Steps to Reproduce

  1. Manually add validation checks in repository functions.
  2. Notice the repeated validation code and the need for a more elegant solution.

Expected Behavior

A Validate decorator should handle model validation, reducing code repetition and improving maintainability.

Actual Behavior

Validation checks are manually implemented in repository functions, leading to repeated code and potential for errors.

Acceptance Criteria

Additional Context

Proposed API Changes

  1. Create Validate Decorator:

    • Develop a Validate decorator to handle model validation.
    import { validate } from 'class-validator';
    import { ValidationError } from 'class-validator';
    
    function Validate(target: any, propertyName: string, descriptor: TypedPropertyDescriptor<Function>) {
     const method = descriptor.value;
    
     descriptor.value = async function (...args: any[]) {
       if (this.config.validateModels) {
         const errors = await validate(args[0]);
    
         if (errors.length) {
           throw new ValidationError(errors);
         }
       }
    
       return method.apply(this, args);
     };
    }
  2. Unit Tests:

    • Create unit tests to validate the functionality of the Validate decorator.
    import { Validate } from './validate.decorator';
    
    class TestClass {
     @Validate
     async someMethod(item: any) {
       // method logic
     }
    }
    
    test('should throw validation errors', async () => {
     const instance = new TestClass();
     instance.config = { validateModels: true };
    
     await expect(instance.someMethod({})).rejects.toThrow(ValidationError);
    });
  3. Replace Existing Validation Code:

    • Refactor existing repository functions to use the Validate decorator instead of manual validation checks.
  4. Ensure Usage of Validate Decorator:

    • Ensure all functions requiring validation are decorated with @Validate.

Example Implementation

@Collection()
class User {
  @IsString()
  id: string;

  @IsString()
  display_name: string;

  @IsString()
  username: string;
}

// Repository instance
class UserRepository {
  @Validate
  async create(user: User) {
    // create logic
  }

  @Validate
  async update(user: User) {
    // update logic
  }
}

Original Issue