Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call external API to download file using NestJS?

Tags:

node.js

nestjs

I want to call external API and then download JSON file in my application. With simple node js project with axios, I can do as below.

const fs = require('fs');

const axios = require('axios').default;


axios.get('https://www.nseindia.com/').then(res => {
  return axios.get('https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY', {
    headers: {
      cookie: res.headers['set-cookie'] 
  }
  })
}).then(res => {
  //console.log(res.data);
  let data = JSON.stringify(res.data)
  fs.writeFileSync('../files/option-chain-indices.json',data);
}).catch(err => {
  console.log(err);
})

this downloads files in folder.

But I cannot figure out, how can I do this with NestJs?

like image 516
Prasad Gavande Avatar asked Oct 26 '25 10:10

Prasad Gavande


1 Answers

I believe what you need to do is create a Service, put your example code into a function, then call that function from a controller or resolver with DI to the Service you just created.

please see sample code below for your reference.

import { Injectable } from '@nestjs/common';
import * as fs from "fs";
import * as axios from "axios";
@Injectable()
export class FileService {
  saveFile() {
    return axios
      .get("https://www.nseindia.com/")
      .then((res) => {
        return axios.get(
          "https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY",
          {
            headers: {
              cookie: res.headers["set-cookie"],
            },
          }
        );
      })
      .then((res) => {
        //console.log(res.data);
        let data = JSON.stringify(res.data);
        fs.writeFileSync("../files/option-chain-indices.json", data);
        return data;
      })
      .catch((err) => {
        console.log(err);
      });
  }
}

can also use HttpModule instead of raw axios as per the nestjs documentation.

like image 120
WTJ Avatar answered Oct 28 '25 22:10

WTJ