简体   繁体   English

如何使用 NestJS 调用外部 API 下载文件?

[英]how to call external API to download file using NestJS?

I want to call external API and then download JSON file in my application.我想调用外部 API 然后在我的应用程序中下载 JSON 文件。 With simple node js project with axios, I can do as below.使用带有 axios 的简单节点 js 项目,我可以执行以下操作。

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?但我不知道,我怎么能用 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.我相信您需要做的是创建一个服务,将您的示例代码放入 function,然后将 function 从 controller 调用到您刚刚创建的解析器。

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.根据nestjs文档,也可以使用HttpModule代替原始axios。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM