如何在NestJS中为第三方API请求创建公共类

发布于 2025-01-09 03:09:20 字数 2749 浏览 0 评论 0原文

我正在创建 NestJS 应用程序,并在其中发出第三方 API 请求。为此,我必须在每个函数中编写相同的内容才能获取数据。

为了使事情不重复,我如何在具有基于 GET 或 POST 请求的 API 请求的公共类上编写并发送响应,以便我可以在每个函数中使用该类。

下面是我的代码:

subscribe.service.ts

@Injectable()
export class SubscribeService {
constructor(@InjectModel('Subscribe') private readonly model:Model<Subscribe>,
            @Inject(CACHE_MANAGER) private cacheManager:Cache,
            private httpService: HttpService){}

 async addSubscriber(subscriberDto:SubscribeDto){
     
    const url = 'https://track.cxipl.com/api/v2/phone-tracking/subscribe';  
    const headersRequest = {
        'content-Type': 'application/json',
        'authkey': process.env.AUTHKEY
    };

    try{

        const resp = await this.httpService.post(url,subscriberDto,{ headers: headersRequest }).pipe(
            map((response) => {

                if(response.data.success == true){
                     const data = new this.model(subscriberDto);
                    // return data.save();
                    const saved = data.save();
                    if(saved){
                        const msgSuccess = {
                                         "success":response.data.success,
                                         "status":response.data.data.status
                                       }
                        return msgSuccess;
                    }
                }
                else{
                    const msgFail = {"success":response.data.success}
                    return msgFail;
                }
            }),
          );
        return resp;
    }
    catch(err){
        return err;
    }
}

 async getLocation(phoneNumber:PhoneNumber){
   
    try{
        
        const location = await this.cacheManager.get<Coordinates>(phoneNumber.phoneNumber);
       
        if(location){
            return location; 
        }
        else{
         
        const resp = await axios.post('https://track.cxipl.com/api/v2/phone-tracking/location',phoneNumber,{headers:{
            'content-Type': 'application/json',
            'authkey': process.env.AUTHKEY
        }});
       
        const msg:Coordinates = {
                                  "location":resp.data.data.location,
                                  "timestamp":resp.data.data.timestamp
                                }
        await this.cacheManager.set<Coordinates>(phoneNumber.phoneNumber,msg, { ttl: 3600 });
        return msg;
        }
     }
     catch(err){
        console.log(err); 
        return err;
     }
   }
}

如上面的代码,在函数 addSubscriber()getLocation() 中,我需要点击重复 API 并一次又一次添加请求标头,有什么方法可以让我为请求和响应创建一个单独的类并在我的服务中使用。

我怎样才能达到想要的结果?

I am creating NestJS application where I am making third-party API requests. For that I have to write the same thing inside every function in order to get the data.

To make things non-repeating, how can I write on common class that has API request based on GET or POST request and send the response so that I can use that class in every function.

Below is my code:

subscribe.service.ts

@Injectable()
export class SubscribeService {
constructor(@InjectModel('Subscribe') private readonly model:Model<Subscribe>,
            @Inject(CACHE_MANAGER) private cacheManager:Cache,
            private httpService: HttpService){}

 async addSubscriber(subscriberDto:SubscribeDto){
     
    const url = 'https://track.cxipl.com/api/v2/phone-tracking/subscribe';  
    const headersRequest = {
        'content-Type': 'application/json',
        'authkey': process.env.AUTHKEY
    };

    try{

        const resp = await this.httpService.post(url,subscriberDto,{ headers: headersRequest }).pipe(
            map((response) => {

                if(response.data.success == true){
                     const data = new this.model(subscriberDto);
                    // return data.save();
                    const saved = data.save();
                    if(saved){
                        const msgSuccess = {
                                         "success":response.data.success,
                                         "status":response.data.data.status
                                       }
                        return msgSuccess;
                    }
                }
                else{
                    const msgFail = {"success":response.data.success}
                    return msgFail;
                }
            }),
          );
        return resp;
    }
    catch(err){
        return err;
    }
}

 async getLocation(phoneNumber:PhoneNumber){
   
    try{
        
        const location = await this.cacheManager.get<Coordinates>(phoneNumber.phoneNumber);
       
        if(location){
            return location; 
        }
        else{
         
        const resp = await axios.post('https://track.cxipl.com/api/v2/phone-tracking/location',phoneNumber,{headers:{
            'content-Type': 'application/json',
            'authkey': process.env.AUTHKEY
        }});
       
        const msg:Coordinates = {
                                  "location":resp.data.data.location,
                                  "timestamp":resp.data.data.timestamp
                                }
        await this.cacheManager.set<Coordinates>(phoneNumber.phoneNumber,msg, { ttl: 3600 });
        return msg;
        }
     }
     catch(err){
        console.log(err); 
        return err;
     }
   }
}

As in above code in both function addSubscriber() and getLocation() I need to hit the API repeatedly and add request headers again and again is there any way so that I can create one separate class for request and response and utilize in my service.

How can I achieve desired the result?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初见 2025-01-16 03:09:21

要在 NestJS 中创建用于发出第三方 API 请求的公共类,您可以按照以下步骤操作:

  1. 在您的 NestJS 项目中创建一个新文件来存储公共类。
    例如,您可以在以下位置创建一个名为 api.service.ts 的文件
    src/common 目录。

  2. 在该文件中,创建一个名为 ApiService 的新类,该类将负责发出 API 请求。这个类应该有一个
    注入必要依赖项的构造函数,例如
    NestJS提供的HttpService。

    从 '@nestjs/common' 导入 { HttpService, Injectable };
    
    @Injectable()
    导出类 ApiService {
      构造函数(私有只读httpService:HttpService){}
    }
    
  3. 为您想要发出的每种类型的 API 请求添加方法到 ApiService 类。例如,您可能有一个用于发出 GET 请求的 get() 方法,一个用于发出 POST 请求的 post() 方法,等等。每个方法都应该接受发出请求所需的参数(例如 URL 和任何查询参数或请求正文),并使用 HttpService 发出请求。

    从 '@nestjs/common' 导入 { HttpService, Injectable };
    
    @Injectable()
    导出类 ApiService {
       构造函数(私有只读httpService:HttpService){}
    
       async get(url: string, params?: object): Promise; {
         return this.httpService.get(url, { params }).toPromise();
       }
    
       async post(url: string, body: object): Promise; {
         返回 this.httpService.post(url, body).toPromise();
       }
     }
    
  4. 在需要发出 API 请求的任何地方注入 ApiService。例如,您可以将其注入到服务或控制器中,并使用 ApiService 的方法发出实际的 API 请求。

    从 '@nestjs/common' 导入 { Injectable } ;
    从'./api.service'导入{ApiService};
    
    @Injectable()
    导出类 SomeService {
      构造函数(私有只读 apiService:ApiService){}
    
      async getData(): Promise; {
        返回 this.apiService.get('https://some-api.com/endpoint');
      }
    }
    

这只是您在 NestJS 中创建用于发出第三方 API 请求的公共类的一种方法。您可以自定义 ApiService 类以满足您的应用程序的特定需求

To create a common class for making third-party API requests in NestJS, you can follow these steps:

  1. Create a new file in your NestJS project to store the common class.
    For example, you could create a file called api.service.ts in the
    src/common directory.

  2. In the file, create a new class called ApiService that will be responsible for making the API requests. This class should have a
    constructor that injects the necessary dependencies, such as the
    HttpService provided by NestJS.

    import { HttpService, Injectable } from '@nestjs/common';
    
    @Injectable()
    export class ApiService {
      constructor(private readonly httpService: HttpService) {}
    }
    
  3. Add methods to the ApiService class for each type of API request you want to make. For example, you might have a get() method for making GET requests, a post() method for making POST requests, and so on. Each method should accept the necessary parameters for making the request (such as the URL and any query parameters or request body), and use the HttpService to make the request.

    import { HttpService, Injectable } from '@nestjs/common';
    
    @Injectable()
    export class ApiService {
       constructor(private readonly httpService: HttpService) {}
    
       async get(url: string, params?: object): Promise<any> {
         return this.httpService.get(url, { params }).toPromise();
       }
    
       async post(url: string, body: object): Promise<any> {
         return this.httpService.post(url, body).toPromise();
       }
     }
    
  4. Inject the ApiService wherever you need to make API requests. For example, you might inject it into a service or a controller, and use the methods of the ApiService to make the actual API requests.

    import { Injectable } from '@nestjs/common';
    import { ApiService } from './api.service';
    
    @Injectable()
    export class SomeService {
      constructor(private readonly apiService: ApiService) {}
    
      async getData(): Promise<any> {
        return this.apiService.get('https://some-api.com/endpoint');
      }
    }
    

This is just one way you could create a common class for making third-party API requests in NestJS. You can customize the ApiService class to meet the specific needs of your application

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文