typescriptnestjsurl-parametershttpmodule

Nestjs httpModule url params as object


Is there a way of passing url params to httpService in nestjs? I'm trying to write this URL in a more accessible way and don't want to use Axios since nest has an HTTPModule.

Here is what I have currently and it works fine but looks bad:

const response = await this.httpService
      .get(`https://api.github.com/users/${username}/repos?per_page=5&sort=created:asc&client_id=${process.env.GITHUB_ID}&client_secret=${process.env.GITHUB_SECRET}`,)
      .toPromise();

I've found this syntax for angular but it's not working:

const response = await this.httpService.get(
      `https://api.github.com/users/${username}/repos`,
      params: {
        per_page: 5,
        sort: created:asc,
        client_id: process.env.GITHUB_ID,
        client_secret: process.env.GITHUB_SECRET
      }).toPromise();

There has to be a way to make it look better.


Solution

  • You're missing the opening and closing brace for the options object.

    const response = await this.httpService.get(
      `https://api.github.com/users/${username}/repos`,
      {
        params: {
          per_page: 5,
          sort: created:asc,
          client_id: process.env.GITHUB_ID,
          client_secret: process.env.GITHUB_SECRET
        }
      }
    ).toPromise();
    

    Without that, you're basically saying use the variable params of type { per_page: 5, sort: created:asc, client_id: process.env.GITHUB_ID, client_secret: process.env.GITHUB_SECRET } (I'd expect Typescript to complain about using values as types here as well)