Open LBeckX opened 1 year ago
@LBeckX did you ever happen to find a solution?
Edit: Should anyone be in dire need of a mapping functionality that works with sequelize, I implemented one myself here: https://github.com/spuxx1701/jslibs/tree/main/packages/nest-utils/src/mapping
It's very simple and easy to extend with more features. Feel free to copy.
@spuxx1701 As I remember, I used the following solutions for the problems.
Install https://github.com/typestack/class-transformer
Create the user entity
User.init({
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
validate: {
isNumeric: true
}
},
username: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [5, 20]
}
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
password: {
type: DataTypes.STRING,
allowNull: true,
}
}, {
tableName: 'User',
sequelize
});
Create a UserDto
export class UserDto {
@Expose()
id: number;
@Expose()
username: string;
}
Create a helper function
export const getUserDto = (obj: any) => plainToInstance(UserDto , obj, {excludeExtraneousValues: true})
It also works with arrays or child entities
@LBeckX Thanks for letting me know! I'll take a look at your solution. Utilizing class-transformer sounds like a good approach since it's commonly part of the nestjs app stack anyways. 🎉
If you use nestjs, I can recommend this article from the documentation.
https://docs.nestjs.com/interceptors
My code to transform all outgoing entites:
transform.interceptor.ts
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
} from '@nestjs/common';
import { map, Observable } from 'rxjs';
import { instanceToPlain } from 'class-transformer';
@Injectable()
export class TransformInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(map((data) => instanceToPlain(data)));
}
}
app.module.ts
...
providers: [
{
provide: APP_INTERCEPTOR,
useClass: TransformInterceptor,
},
],
...
Is there an existing issue for this?
Describe the issue
Sequelize map is empty
Models/DTOs/VMs
Mapping configuration
No response
Steps to reproduce
npm i @automapper/core @automapper/classes @automapper/sequelize
Expected behavior
Screenshots
No response
Minimum reproduction code
No response
Package
Other package and its version
No response
AutoMapper version
8.7.7
Additional context
Node: v18.14.0