'How to create common class for third-party API requests in NestJS

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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source