AutoEncoder is a base class that makes objects easily encodable, decodable and patchable by using TypeScript decorators.
AutoEncoder uses the @field TypeScript decorator to mark all properties that should be encoded, and how they should be encoded. You pass a Decoder class for each property.
Her is an example:
import { Encodeable, StringDecoder, NumberDecoder, field } from "@simonbackx/simple-encoding";
class MyClass extends AutoEncoder {
@field({ decoder: NumberDecoder })
id: number;
@field({ decoder: StringDecoder })
name: string;
@field({ decoder: MyClass, nullable: true })
other: MyClass | null = null;
writeName() {
console.log(this.name);
}
}
const test = MyClass.create({ id: 123, name: "Hello world" });
const test2 = MyClass.create({ id: 123, name: "Hello world", other: test });
// Simulate a network or file storage by converting to JSON
// You can also convert it to a different storage type
const json = JSON.stringify(test2.encode({ version: 1 }));
// ... Store or send the JSON somewhere
// Decode from JSON
const plainObject = JSON.parse(json);
const data = new ObjectData(plainObject, { version: 1 });
const instance = MyClass.decode(data);
// Decode throws if fields are missing or types are not okay.
// You can use the errors to provide good errors in you API's that help developers to
// point out the missing fields or types.
// Now all methods are available again
instance.writeName();
Now, say we want to change the type of id to a string and we want to have an extra field called createdAt. We can use versioning for this.
Sometimes, TypeScript can’t properly infer the right type when you use AutoEncoders. In these cases you’ll have to manually add as Decoder<T> :
// 🚫 Doesn't work
// response.data is of type AutoEncoder
const response = server.request({
method: "GET",
url: "/dogs/123",
decoder: Dog
});
// ✅ Does work
// response.data is of type Dog
const response = server.request({
method: "GET",
url: "/dogs/123",
decoder: Dog as Decoder<Dog>
});
// ✅ Does work
// response.data is of type Dog[]
const response = server.request({
method: "GET",
url: "/dogs",
decoder: new ArrayDecoder(Dog as Decoder<Dog>)
});