|
| 1 | +import { unlinkSync, writeFileSync } from "fs"; |
| 2 | +import { tmpdir } from "os"; |
| 3 | +import { join } from "path"; |
| 4 | + |
| 5 | +import { client } from ".."; |
| 6 | + |
| 7 | +import { NextFunction, Request, Response } from "../interfaces/base.interface"; |
| 8 | +import { STATUS } from "../utils/constant.util"; |
| 9 | +import { BadRequestError } from "../utils/error.util"; |
| 10 | +import { Helper } from "../utils/helper.util"; |
| 11 | + |
| 12 | +export const sendMsg = async ( |
| 13 | + req: Request, |
| 14 | + res: Response, |
| 15 | + next: NextFunction |
| 16 | +) => { |
| 17 | + try { |
| 18 | + const { content, number } = req.body; |
| 19 | + const helper = new Helper(); |
| 20 | + |
| 21 | + if (!content) throw new BadRequestError("No message content provided!"); |
| 22 | + if (!helper.isValidPhoneNumber(number)) |
| 23 | + throw new BadRequestError("Phone number is not valid! Format: 62..."); |
| 24 | + |
| 25 | + client.sendMsg(content, number); |
| 26 | + |
| 27 | + const result = { |
| 28 | + status: "success", |
| 29 | + code: 200, |
| 30 | + message: "Message sucessfully sent", |
| 31 | + data: { |
| 32 | + number, |
| 33 | + content, |
| 34 | + type: "text", |
| 35 | + }, |
| 36 | + }; |
| 37 | + res.status(STATUS.SUCCESS).json(result); |
| 38 | + } catch (error) { |
| 39 | + return next(error); |
| 40 | + } |
| 41 | +}; |
| 42 | + |
| 43 | +export const sendMedia = async ( |
| 44 | + req: Request, |
| 45 | + res: Response, |
| 46 | + next: NextFunction |
| 47 | +) => { |
| 48 | + try { |
| 49 | + const { content, number } = req.body; |
| 50 | + const helper = new Helper(); |
| 51 | + |
| 52 | + if (!req.file) throw new BadRequestError("No file were provided!"); |
| 53 | + if (!helper.isValidPhoneNumber(number)) |
| 54 | + throw new BadRequestError("Phone number is not valid! Format: 62..."); |
| 55 | + |
| 56 | + const tempFilePath = join(tmpdir(), req.file.originalname); |
| 57 | + writeFileSync(tempFilePath, req.file.buffer); |
| 58 | + |
| 59 | + client.sendFile(content, number, tempFilePath).then(() => { |
| 60 | + unlinkSync(tempFilePath); |
| 61 | + }); |
| 62 | + |
| 63 | + const result = { |
| 64 | + status: "success", |
| 65 | + code: 200, |
| 66 | + message: "Message sucessfully sent", |
| 67 | + data: { |
| 68 | + number, |
| 69 | + content, |
| 70 | + type: "media", |
| 71 | + }, |
| 72 | + }; |
| 73 | + |
| 74 | + res.status(STATUS.SUCCESS).json(result); |
| 75 | + } catch (error) { |
| 76 | + console.log(error); |
| 77 | + return next(error); |
| 78 | + } |
| 79 | +}; |
0 commit comments