Abstract
Converts the Data
object into a plain JSON representation, including all
properties defined as getters in the subclass.
The toJSON
method dynamically identifies getter properties in the
subclass and collects their values to construct a JSON object. This is
particularly useful when you want to serialize the Data
object for APIs,
logging, or other use cases requiring JSON format.
A plain object representing the Data
instance with all getter properties.
class LoginData extends Data<FormParser> {
get username() {
return this.parser.getString("username");
}
get password() {
return this.parser.getString("password");
}
}
const loginData = new LoginData(new FormParser(formData));
console.log(JSON.stringify(loginData.toJSON()));
// Output: { "username": "johndoe", "password": "secret" }
The
Data
class is an abstract representation of a Data Transfer Object (DTO) designed to safely parse and expose data from various structured sources likeFormData
,URLSearchParams
, or JSON objects.Developers can extend this class to define specific DTOs that map to incoming structured data, providing a type-safe way to access required fields.
Usage
Data
is designed to be subclassed, where the subclass defines properties that extract specific values from the providedParser
. TheParser
is responsible for retrieving values from the underlying data source (e.g.,FormData
, JSON).The primary goal is to standardize data access and ensure the presence of required fields via the parser. This pattern is particularly useful in handling form submissions (e.g., in Remix actions) by validating the structure of incoming data against the defined DTO.
How It Works
Parser
to extract a specific value from the input.getString
orgetNumber
) ensure that the data is present and correctly typed, throwing errors if validation fails.parser.has()
) before accessing the value.Method
toJSON Returns a JSON representation of the DTO, with all defined getter properties.
Example