For example, I have entity Person
which can be obtained from DB, or inserted into DB.
class Person {
id: number;
name: string;
age: number;
}
id
field is autogenerated column in DB, so in situation when model is obtained from DB it will be always filled.
But when creating model, we are to set name
and age
fields.
So, in case, when we getting model from DB - id
field is not optional and is always set. In case when we creating new model to insert into DB id
field should be unset, and therefore in model definition should be optional.
Are there any best practices or common approaches to handle this problem?
CodePudding user response:
You could create an interface and add one more layer of abstraction such as:
interface Entity {
id: string;
}
interface IPerson {
name: string;
age: number;
}
class Person implements Entity, IPerson {
id: string;
name: string;
age: number;
}
class PersonInput implements IPerson {
name: string;
age: number;
}
However, I would probably just sanitize, validate, and insert the values directly into DB without turning them into a class instance.
CodePudding user response:
Consider this code:
interface PersonInput {
name: string;
age: number
}
interface PersonOutput extends PersonInput {
id: string
}
class PersonInput implements PersonInput {
constructor(public name: string, public age: number) { }
}
const personInput = new PersonInput('John', 42)
AFAIK, you are not allowed to create PersonOutput
object with id
- you can only obtain it from your DB. Hence I think that your PersonInput
class should expect only two properties name
and age
. Since, PersonOutput
is a subtype of PersonInput
, you should have some base interface, like interface PersonInput
.
Interface PersonOutput
should extends PersonInput
. That's all.