UNPKG

@jaguarsolucoes/correios

Version:

Biblioteca cliente de informações dos correios.

69 lines (68 loc) 2.77 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.convertHtmlToEvento = exports.rastrear = void 0; const cheerio_1 = __importDefault(require("cheerio")); const axios_1 = __importDefault(require("axios")); ; ; const rastrear = async (codigo) => { return axios_1.default({ method: 'GET', url: `https://www.linkcorreios.com.br/${codigo}`, headers: { "content-type": "text; charset=utf-8", "cache-control": "no-cache", }, }).then(resp => { const eventos = exports.convertHtmlToEvento(resp.data); console.log(resp.data); return { eventos }; }); }; exports.rastrear = rastrear; const convertHtmlToEvento = (htmlString) => { const html = cheerio_1.default.load(htmlString); const elemArray = []; html("ul.linha_status").each((_, elem) => { elemArray.push(elem); }); const elemMap = elemArray.map((elem) => { const mapObj = {}; html(elem) .find("li") .each((_, liElem) => { var _a, _b; const text = html(liElem).text(); if (text) { mapObj.status = ''; // TODO: pendente, entregue, falha if (text.includes("Status")) mapObj.nome = text.replace('Status:', '').trim(); if (text.includes("Data")) { const regex = /([0-2][0-9]|(3)[0-1])(\/)(((0)[0-9])|((1)[0-2]))(\/)\d{4}/gm; const strDate = (_a = regex.exec(text)) === null || _a === void 0 ? void 0 : _a[0]; if (strDate) { const dateParts = strDate.split("/"); // month is 0-based, that's why we need dataParts[1] - 1 mapObj.data = new Date(+dateParts[2], Number(dateParts[1]) - 1, +dateParts[0]); } } if (text.includes("Data")) { const regex = /([0-9][0-9])(:)([0-9][0-9])/gm; mapObj.hora = (_b = regex.exec(text)) === null || _b === void 0 ? void 0 : _b[0]; } if (text.includes("Local")) mapObj.local = text.replace('Local:', '').trim(); if (text.includes("Origem")) mapObj.origem = text.replace('Origem:', '').trim(); if (text.includes("Destino")) mapObj.destino = text.replace('Destino:', '').trim(); } }); return mapObj; }); return elemMap.reverse(); }; exports.convertHtmlToEvento = convertHtmlToEvento;