firebase / firebase-functions

Firebase SDK for Cloud Functions
https://firebase.google.com/docs/functions/
MIT License
1.02k stars 201 forks source link

Fixes encoding of circular referenced object / complex object #1525

Open DavidWeiss2 opened 7 months ago

DavidWeiss2 commented 7 months ago

Description

This PR enhances Firebase functions v2 by fixing an issue related to encoding objects with self-references, which previously led to "Maximum call stack size exceeded" errors. The change is to throw a clear error on what is the error (not JSON serializable, with object ref in console).

For a practical demonstration, consider a class instance with self-referencing properties. The updated encoding function now throws Data cannot be encoded in JSON: [object: object] in such cases, preventing stack overflow errors and ensuring the encoded output reflects the object's structure accurately, without infinite recursion. This improvement is verified through comprehensive test case included in the PR.

It fixes #1527

Code sample

See test cases. The code before the change will give "Maximum call stack size exceeded" even on the basic case:

    class TestClass {
      foo: string;
      bar: number;
      self: TestClass;
      constructor(foo: string, bar: number) {
        this.foo = foo;
        this.bar = bar;
        this.self = this;
      }
    }
    const testObject = new TestClass("hello", 1);
    expect(()=>https.encode(testObject)).to.throw.(`Data cannot be encoded in JSON: ${testObject}`);
DavidWeiss2 commented 6 months ago

Refactored to reflect team decision on throwing in the case of self ref. https://github.com/firebase/firebase-functions/issues/1527#issuecomment-2014179765 @inlined

DavidWeiss2 commented 1 week ago

@inlined Can we get update on this PR status?