Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create common source for different services with NestJS?

For example, this is book.service.ts

    import { Injectable } from "@nestjs/common";
    import { Book } from '../interfaces/book.interface'

    @Injectable()
    export class BooksService {
        private readonly books: Book[] = [];

        private create(book: Book) {
            console.log(book)
            this.books.push(book);
        }

        private findAll(): Book[] {
            return this.books;
        }
    }

Another buy.service.ts

    import { Injectable } from "@nestjs/common";
    import { Book } from '../interfaces/book.interface'

    @Injectable()
    export class BuyService {
        private readonly books: Book[] = [];

        private findAll(): Book[] {
            return this.books;
        }
    }

The private findAll() methods are the same in the two files. How to create a common logic for them?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If I were you, I’d inject the BookService into the BuyService and not make the findAll() method private. This way you can call this.bookService.findAll() from within the BuyService. Otherwise, you’ll need to abstract up another layer and inject that abstraction into both BookService and BuyService.

Sounds like overall tightly coupling code, so be cautious you don’t end up with crossed domain lines and tightly coupled dependencies

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading