All files index.ts

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64  1x   1x     2x         2x     2x       2x   2x 2x           2x               2x       2x 2x                             1x                
import { IConfig, IMessage, IBodyMaytapi, IResponse } from "./types";
import  * as request from 'request-promise'
 
export class ElisaWhatsApp{
    
    private config:IConfig
    private authorizationHeaders = {
        "x-maytapi-key":""
    }
 
    constructor(config:IConfig){
        this.config = config
 
        // set authorization key
        this.authorizationHeaders["x-maytapi-key"] = config.apiKey
    }
 
    public async sendMessage(message:IMessage):Promise<IResponse>{
        let bodyOfMessage:IBodyMaytapi = {to_number:"",type:"",message:""}
 
        Eif(message.type === "text"){
            bodyOfMessage = {
                "to_number":message.numberTo,
                "type":message.type,
                "message":message.message
            }
        }
        Iif(message.type === "link"){
            bodyOfMessage = {
                "to_number":message.numberTo,
                "type"     :message.type,
                "message"  :message.link,
                "text"     :message.message
            }
        }
        return await this.callService(bodyOfMessage)
    }
 
    private callService(body:IBodyMaytapi):Promise<IResponse>{
        return new Promise((resolve,reject) =>{
            request.post(
                {
                    url:this.config.url,
                    headers: this.authorizationHeaders,
                    json: true,
                    body
                }
            ).then((res:any) =>{
                resolve({
                    ok:res.success,
                    status:200,
                    message:res.message
                })
            })
            .catch((err:any) =>{
                reject({
                    ok:false,
                    status:err.statusCode,
                    message:err.message
                })
            })
        });
    }
}