I am trying to define my data structure to encapsulate the logic for working with data in one class. I then have the Field class that has this information.
Field<T>(private name:string, private size:number, private comment:string) {
}
get Name():string {
return this.name;
}
get Size():number {
return this.size;
}
Create a Field reference:
class User {
public FirstName:Field<string> = new Field<string>('FirstName', 20);
public LastName:Field<string> = new Field<string>('LastName', 32);
public Age:Field<number> = new Field<number>('Age', 3);
}
The above means I have a data field 'FirstName' which is a string and maximum of 20 characters. 'LastName' is a 32 character string and Age can be 3 digits.
I use this to then be able to validate my data on a form (using the Size for instance to limit the number of characters that could be entered) as well as when reading from an external API.
If I am getting the data from an external API, I can also use the field 'Size' to limit the amount of data I copy into the field, so as to truncate the data.
This allows my data interface layer to work with a data type class, expecting all fields to be Field<T>, and then allows me to use my library functions to control the data size, add data validation to forms etc., without always having to write the validate functions in the HTML, since I can use loops in Angular and extract the information from the data structure.
My question now is how to get a generic interface for working with data coming from lists and objects in AngularFire.
Normally, when accessing data and the structure from AngularFire, I can use:
constructor(public afDb:AngularFireDatabase) {
...
this.afDb.object<IUser>('/user/1').valueChanges();
...
}
This would get the data and automatically parse it into the IUser interface (not shown above).
I want to be able to generate an IUser interface from my User class which has the data structures in the Field<T>. Basically I want to generate an interface from the User class something like:
export interface IUser {
FirstName?:string;
LastName?:string;
Age?:number;
}
Then this interface could be used in my access to AngularFire. The other option/question would be how to do the equivalent of the afDb.object<IUser>... and leave the <IUser> off, but be able to parse the results from the AngularFire object into my data structure which is the User class. So the parsing would call Field<T>.SetValue(); or something.