I'm currently working on a NestJS project where I need to save an array of objects in a one-to-many relationship.
The frontend provides me with the following structure:
[
{
"actor":"actorname",
"role":"actorrole"
},
{
"actor":"actorname2",
"role":"actorrole2"
}
]
To achieve this, I have created entities for movies and actors as follows:
actor.entity.ts
//imports
@Entity()
export class Actor {
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(() => Movie, (movie) => movie.actors)
movieId: number;
@Column()
role: string;
@Column()
actor: string;
}
movie.entity.ts
//imports
@Entity()
export class Movie {
@PrimaryGeneratedColumn()
id: number;
//more stuff
@OneToMany(() => Actor, (actor) => actor.movieId)
actors: Actor[];
}
The challenge lies in the fact that the frontend sends the JSON data as a single string. Therefore, I need to parse it before accepting it in my DTO like so:
//imports
export class CreateMovieDto {
actorsArray: string;
}
My current hurdle is saving the parsed JSON data:
//imports
@EntityRepository(Movie)
export class MoviesRepository extends Repository<Movie> {
async createMovie(
createMovieDto: CreateMovieDto,
fileName: string,
filePath: string,
) {
const movie = this.create(createMovieDto);
let actorsArray = JSON.parse(createMovieDto.actorsArray);
//how do i save it now together with the movie?
try {
//await this.save(movie); disabled for now
return movie;
} catch (error) {
if ((error.code = 'ER_DUP_ENTRY')) {
console.log(error);
throw new ConflictException('Movie already exists');
} else {
console.log(error);
throw new InternalServerErrorException();
}
}
}