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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With