'Converting a sequelize model class object to a seperate entity class object in typescript
I have sequelize setup in my nest js project, and I have response entity classes which contain decorators from class-transformer to hide unnecessary information from responses via transformer middlewares.
I managed to write a function that can do this conversion using es2015's Object.assign
export function getEntityFromModel<T>(cls: new () => T, item: Model): T;
export function getEntityFromModel<T>(cls: new () => T, item: Model[]): T[];
export function getEntityFromModel<T>(
cls: new () => T,
items: Model | Model[],
): T | T[] {
if (Array.isArray(items)) {
const objects = items.map<T>((item) =>
Object.assign(new cls(), item.get()),
);
return objects;
} else {
return Object.assign(new cls(), items.get());
}
}
@Table({ tableName: 'A' })
export class ModelA extends Model<A> {
@Column({ primaryKey: true, allowNull: false, type: DataType.STRING })
id: string;
@Column({ allowNull: false, type: DataType.STRING(20) })
col1: string;
@Column({ allowNull: false, type: DataType.STRING(20) })
col2: object;
}
export class EntityA {
id: string;
col1: string;
@Exclude
col2: object;
}
getEntitiyFromModel(EntityA, modelAObj)
Now, this works as intended but the problem remains that typescript will complain about the additional keys in the Model type (also ts does not assert that cls and T should have same attributes)
Type 'EntityA' is missing the following properties from type 'ModelA': $add, $set, $get, $count, and 32 more.ts(2740)
What could be a more neater solution
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
