Nest.js troubleshooting
Samir ⚽⚽⚽
0
Reputation points
I need some basic frontend to this code in nest.js my backend looks like this:
nestjs controller: @Controller('authors')
export class AuthorsController {
constructor(
private readonly authorsService: AuthorsService
) {}
@Get()
getAuthors() {
return this.authorsService.getAuthors();
}
@Get('/:id')
getAuthor(
@Param('id') authorId: number
): Promise<Author> {
return this.authorsService.getAuthor(authorId);
}
@Post()
createAuthor(
@Body() authorDto: AuthorDto
): Promise<Author> {
return this.authorsService.createAuthor(authorDto);
}
@Put('/:id')
editAuthor(
@Param('id') authorId: number,
@Body() authorDto: AuthorDto
): Promise<Author> {
return this.authorsService.editAuthor(authorId,authorDto);
}
@Delete('/:id')
deleteAuthor(
@Param('id') authorId: number
): Promise<Author> {
return this.authorsService.deleteAuthor(authorId);
}
}
SERVICE
nestjs service: @Injectable()
export class BooksService {
constructor(
@InjectRepository(Book)
private booksRepository: Repository<Book>
) {}
getBooks(): Promise<Book[]> {
return this.booksRepository.find({
relations: ['author'],
});
}
getBook(id: number): Promise<Book> {
return this.booksRepository.findOne( {
where: { id },
relations: ['author'],
});
}
async createBook(data: BookDto): Promise<Book> {
const book = this.booksRepository.create({
...data,
author: { id: data.authorId},
});
return this.booksRepository.save(book);
}
async editBook(id: number, data: BookDto): Promise<Book> {
const book = await this.booksRepository.findOne({
where: { id },
relations: ['author'],
});
if(!book) {
throw new NotFoundException('Book does not exist');
}
book.author = new Author();
book.author.id = data.authorId;
book.title = data.title;
book.year = data.year;
return this.booksRepository.save(book);
}
async deleteBook(id: number): Promise<Book> {
const book = await this.booksRepository.findOne({ where: {id} });
if(!book) {
throw new NotFoundException('Book does not exists');
}
return this.booksRepository.remove(book);
}
}
MODULE
nestjs module: @Module({
imports: [
TypeOrmModule.forFeature([Book])
],
controllers: [BooksController],
providers: [BooksService],
})
export class BooksModule {}
ENTITY
nestjs entity: @Entity()
export class Book {
@PrimaryGeneratedColumn()
id:number;
@ManyToOne(
type => Author,
a => a.books,
)
author: Author;
@Column()
title: string;
@Column()
year: number;
}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,431 questions
Sign in to answer