Setting a type `ctor` fails if called before the type is registered into the namespace
protobuf.js version: 7.4.0
Setting a type ctor fails if called before the type is registered into the namespace.
Let's consider the following code:
import {Field, Message, Root, Type} from "protobufjs";
export const namespace = new Root();
const anyType = new Type('Any')
.add(new Field('y', 1, 'string'));
const fooType = new Type('Foo')
.add(new Field('x', 1, 'Any'));
fooType.ctor = class extends Message {
};
namespace
.add(anyType)
.add(fooType);
fooType.create({
x: true
});
This code fails with a Error: no such Type or Enum 'Any' in Type Foo error.
Now, let's try registering the ctor of fooType after the type was registered into the namespace.
import {Field, Message, Root, Type} from "protobufjs";
export const namespace = new Root();
const anyType = new Type('Any')
.add(new Field('y', 1, 'string'));
const fooType = new Type('Foo')
.add(new Field('x', 1, 'Any'));
namespace
.add(anyType)
.add(fooType);
fooType.ctor = class extends Message {
};
fooType.create({
x: true
});
This time, the code succeeds.
Except if I missed something, this requirement to have the ctor property set after a type is registered into the namespace is not documented.
Ot maybe it is a bug. I understand that the type Foo depends on the type Bar, but it seems very unexpected that the ctor setter actually checks the existence of the other types before proceeding. I assumed it would be deffered until execution (i.e. calls to create or toObject).
If it is a design decision, I'd be curious to understand its rational. Regardless, I think it needs to be documented. I spent a lot of time trying to figure out the issue and I assume I've not been the only one and won't be the last.