I'm encountering an issue while trying to pass two parameters using the spread operator from the book.controller to the book.service.ts service. The error message I'm receiving is:
Spread types may only be created from object types
It's worth mentioning that passing a single parameter with the spread operator works fine.
Below are snippets of the controller and service files:
book.controller.ts
@Controller('book')
export class BookController {
constructor(
private readonly _bookService: BookService
) { }
//it works
@Post()
@Roles(RoleType.ADMIN, RoleType.MANAGER)
@UseGuards(AuthGuard(), RoleGuard)
@UseInterceptors(FileInterceptor('image'))
createBook(@UploadedFile() file: any, @Body() role: Partial<CreateRoleDto>) {
return this._bookService.create({
...role,
image: file?.filename
});
}
//The error occurs in this request
@Post('author')
@Roles(RoleType.GUEST)
@UseGuards(AuthGuard(), RoleGuard)
@UseInterceptors(FileInterceptor('image'))
createBookByAuthor(@UploadedFile() file: any, @Body() role: Partial<CreateBookDto>, @GetUser('id') authorId: number) {
return this._bookService.createByAuthor({
...role,
...authorId,
image: file?.filename
})
}
}
book.service.ts
@Injectable()
export class BookService {
constructor(
@InjectRepository(BookRepository)
private readonly _bookRepository: BookRepository,
@InjectRepository(UserRepository)
private readonly _userRepository: UserRepository
) { }
async create(book: Partial<CreateBookDto>): Promise<ReadBookDto> {
const authors: User[] = [];
for (const authorId of book.authors) {
const authorExists = await this._userRepository.findOne(authorId, {
where: { status: status.ACTIVE }
});
if (!authorExists) {
throw new NotFoundException(
`There's not an author with this id: ${authorId}`
);
};
const isAuthor = authorExists.roles.some(
(role: Role) => role.name === RoleType.GUEST
);
if (!isAuthor) {
throw new UnauthorizedException(
`This user ${authorId} is not an author`
)
}
authors.push(authorExists);
}
const savedBook: Book = await this._bookRepository.save({
name: book.name,
description: book.description,
image: book.image,
authors
})
return plainToClass(ReadBookDto, savedBook);
}
async createByAuthor(book: Partial<CreateBookDto>, authorId: number): Promise<ReadBookDto> {
const author = await this._userRepository.findOne(authorId, {
where: { status: status.ACTIVE }
});
const isAuthor = author.roles.some(
(role: Role) => role.name === RoleType.GUEST
);
if (!isAuthor) {
throw new UnauthorizedException(`This user ${authorId} is not an author`)
}
const savedBook: Book = await this._bookRepository.save({
name: book.name,
description: book.description,
image: book.image,
authors: [author]
});
return plainToClass(ReadBookDto, savedBook);
}
}
Any help would be greatly appreciated! Thank you!