I've got the following code
export interface UserModel {
id: string;
email: string;
password: string;
firstName: string;
lastName: string;
}
This model defines the DB model. I also have the interface that is used as a response from the API.
export type UserGetResponse = Omit<UserModel, "id" | "password">;
I don't want to respond with the id
and password
properties. Later when fetching the data from DB I do something like this
User.scan().then((users: UserModel[]) => users.map((user: UserModel) => user as UserGetResponse))
but the id
and password
are not removed from the response. Is there any better way to do this. Should I create a class with a constructor which gets UserModel object and assigns only properties I need?
CodePudding user response:
You can do this with a blacklist approach. Something like:
User
.scan()
.then((users: UserModel[]) => users.map((user: UserModel) => {
...user,
id: undefined,
password: undefined,
} as UserGetResponse))
Or better yet you can do it with a whitelist approach. Something like:
User
.scan()
.then((users: UserModel[]) => users.map((user: UserModel) => {
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
} as UserGetResponse))
The white list it better in my opinion as it has no risk of including more properties automatically if/when the data structure gets extended.