0

I am new and learning Nest JS, i came from Java Springboot before. In Java Springboot, if my Rest API have one request let's say my API will always have 10 second to finish, the first one won't block the second request, the second request just start without waiting for the first request to finish.

When i trying Nest JS, i have read that Nest JS is build on top of Nodejs which is single threaded, so if the same condition just like my Java Springboot REST API happend, it will block the first request and wait it to finish then process the second one right?

But when i read in some articles, we can write the non-blocking one, here is what i try :

@Controller()
export class AppController {
  @Get()
  findAllX(): Observable<string> {
    console.log('Before sleep');

    // Sleep for 10 seconds (10000 milliseconds) asynchronously
    // here i mocking my slow database query
    return timer(10000).pipe(
      switchMap(() => of('Sleep completed'))
    );
  }

  @Get('test')
  async findAllY(): Promise<string> {
    console.log('Before sleep');

    // Sleep for 10 seconds (10000 milliseconds) asynchronously
    // here i mocking my slow database query
    await new Promise((resolve) => setTimeout(resolve, 10000));

    console.log('After sleep');

    return 'Sleep completed';
  }
}

as you can see i mocking my slow database query using timer and setTimeout, my first function named "findAllX" is written and return as Observable, but then i request TWICE for this REST API, it wait for the first one to complete then start the second one

it applied the same with Promise approach.

How can i make it handle request like java springboot?

**Notes :

cmd to init my project : nest new project-name --strict

cmd to start my project : npm run start:dev -- -b swc

Testing scenario :

- Using Web Browser :

since my API is writtin with Get Request, i use browser and open two tab then i hit my API request at the first tab then switch to the second one. When i see at my terminal, the console.log of the second request doesn't print console.log until the first request to finish.

- But.. When i try using POSTMAN :

It worked! it didn't wait the first one to finish, i try both approach it worked.

- I write simple angular client then hit my API, here is the result :

enter image description here

i clicked it rapidly, as you can see the api getting slower 10 second for 3 request and the rest is not! the connection id written the same id for the first 3 request and you can see the waterfall, what happened?

UPDATE Angular Codes :

api.service.ts :
@Injectable({
  providedIn: 'root'
})
export class ApiService {
  private apiUrl = 'http://localhost:3000';

  constructor(private http: HttpClient) {}

  getData(): Observable<any> {
    return this.http.get(`${this.apiUrl}`);
  }
}

here is my api-button.component.ts :

@Component({
  selector: 'app-api-button',
  templateUrl: './api-button.component.html',
  styleUrls: ['./api-button.component.scss']
})
export class ApiButtonComponent {
  responseData: any;

  constructor(private apiService: ApiService) {}

  fetchData(): void {
    this.apiService.getData().subscribe(
      (data) => {
        this.responseData = data;
        // You can process the API response data here
      },
      (error) => {
        console.error('Error:', error);
      }
    );
  }
}

here is the html :

<div>
  <button (click)="fetchData()">Fetch Data</button>
</div>
Ke Vin
  • 3,478
  • 11
  • 60
  • 91
  • 2
    "*i request TWICE for this REST API, it wait for the first one to complete then start the second one*" - it should not. Can you show us how you did the requests? – Bergi Aug 27 '23 at 16:38
  • oh sure, since my API is writtin with Get Request, i use browser and open two tab then i hit my API request at the first tab then switch to the second one. When i see at my terminal, the console.log of the second request doesn't print console.log until the first request to finish.. Is there anything i missed? – Ke Vin Aug 27 '23 at 16:41
  • 4
    You are making 10s wait for each api and if you do the call manually, then you will surely get the lagging behavior. Try a separate script file for imitating the api calls at same time, the lag should be minimal as expressjs supports concurrent requests – Kaneki21 Aug 27 '23 at 16:44
  • 3
    Sounds like your browser is just rate-limiting requests per domain (although I wouldn't have expected this across tabs). Or maybe it is waiting for the first request to finish as it expects the result to be cached, if you are doing multiple GET requests for the exact same resource (URL). – Bergi Aug 27 '23 at 16:55
  • sorry i undelete my question since i try write simple angular client to consume my API, it still blocked – Ke Vin Aug 27 '23 at 17:20
  • @Kaneki21 i have write a simple API call using angular and you can see the result when i rapidly hit my API, it increase api call time for the first 3 request, what happend? – Ke Vin Aug 27 '23 at 17:35
  • Hope [this](https://stackoverflow.com/questions/34855352/how-in-general-does-node-js-handle-10-000-concurrent-requests) helps. Once again you can simply trigger parallel requests using `Promise.all` and try to debug. – Kaneki21 Aug 27 '23 at 18:37
  • 1
    @KeVin You'll need to post the angular code that does the api calls if you need help with it – Bergi Aug 27 '23 at 20:38
  • @Bergi pardon, i just update my question :D – Ke Vin Aug 28 '23 at 01:12

0 Answers0