Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 65 66 67 68 69 70 71 72 | 1x 1x 1x 1x 1x 1x 1x 3x 1x 3x 3x 11x 11x 11x 11x 11x 3x 3x 3x 3x 3x 11x 3x 3x 11x 11x 11x 3x 1x | import cheerio from 'cheerio';
import axios from 'axios';
export interface Rastreio {
eventos?: Evento[],
};
export interface Evento {
status?: string,
nome?: string,
data?: Date,
hora?: string,
local?: string,
origem?: string,
destino?: string,
};
export const rastrear = async (codigo: string): Promise<Rastreio> => {
return axios({
method: 'GET',
url: `https://www.linkcorreios.com.br/${codigo}`,
headers: {
"content-type": "text; charset=utf-8",
"cache-control": "no-cache",
},
}).then(resp => {
const eventos: Evento[] = convertHtmlToEvento(resp.data);
console.log(resp.data)
return { eventos } as Rastreio;
});
};
export const convertHtmlToEvento = (htmlString: string): Evento[] => {
const html = cheerio.load(htmlString);
const elemArray: CheerioElement[] = [];
html("ul.linha_status").each((_, elem) => {
elemArray.push(elem);
});
const elemMap = elemArray.map((elem) => {
const mapObj: Evento = {};
html(elem)
.find("li")
.each((_, liElem) => {
const text = html(liElem).text();
Eif (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 = regex.exec(text)?.[0];
Eif (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 = regex.exec(text)?.[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();
}; |