elersong / fireorm24

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

Handle Undefined Values by Setting Them as Null #19

Open elersong opened 3 months ago

elersong commented 3 months ago

Description

To improve query capabilities and data consistency in Fireorm, undefined values in a collection should be set to null. This change would allow querying those values using Where clauses. Additionally, the IFirestoreVal type should be extended to allow null values.

Steps to Reproduce

  1. Create a Fireorm entity with optional fields.
  2. Attempt to query documents where these fields are undefined.

Expected Behavior

Undefined fields should be stored as null in Firestore, allowing queries to include conditions on these null values.

Actual Behavior

Undefined fields are not stored, making it impossible to query for documents based on undefined values.

Acceptance Criteria

Additional Context

Proposed API Changes

  1. Modify serializeEntity Function:

    • Update the serializeEntity function to convert undefined values to null before saving to Firestore.
    function serializeEntity(entity: any): any {
     const serializedEntity = { ...entity };
     Object.keys(serializedEntity).forEach(key => {
       if (serializedEntity[key] === undefined) {
         serializedEntity[key] = null;
       }
     });
     return serializedEntity;
    }
  2. Extend IFirestoreVal Type:

    • Update the IFirestoreVal type def to include null
    export type IFirestoreVal = string | number | boolean | null | ...; // other existing types
  3. Querying Null Values:

    • Ensure that the Where query functionality supports conditions on null values
    // Example query
    getRepository(MyEntity).where('myField', '==', null).find();    

Example Usage

// Define an entity with optional fields
@Collection()
class MyEntity {
  id: string;
  optionalField?: string;
}

// Save an entity with undefined optionalField, which will be stored as null
const entity = new MyEntity();
entity.id = '123';
await getRepository(MyEntity).create(entity);

// Query for entities where optionalField is null
const results = await getRepository(MyEntity).where('optionalField', '==', null).find();

Original Issue