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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
/**
* A fake cep.is, so the test suite never touches the network.
*
* Same routes, bodies and status codes as the real API, plus a request log the
* tests assert on. It listens on every interface because two different clients
* have to reach it: the browser on the host, and PHP inside the WordPress
* container through the `fakecep` host alias.
*
* @module
*/
const ADDRESSES = {
"01001000": {
cep: "01001000",
logradouro: "Praça da Sé",
complemento: "lado ímpar",
unidade: "",
bairro: "Sé",
localidade: "São Paulo",
uf: "SP",
estado: "São Paulo",
regiao: "Sudeste",
ibge: "3550308",
gia: "1004",
ddd: "11",
siafi: "7107",
geo: { lat: -23.567202, lon: -46.649659, raio_m: 1084, precisao: "logradouro" },
},
20040020: {
cep: "20040020",
logradouro: "Avenida Rio Branco",
complemento: "até 0999 - lado ímpar",
unidade: "",
bairro: "Centro",
localidade: "Rio de Janeiro",
uf: "RJ",
estado: "Rio de Janeiro",
regiao: "Sudeste",
ibge: "3304557",
gia: "",
ddd: "21",
siafi: "6001",
},
};
const HEADERS = {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json; charset=utf-8",
};
/**
* Start the fake API.
*
* `state.requests` collects `{cep, userAgent}` for every lookup, which is how
* the proxy tests prove the request came from PHP rather than the browser.
*
* @param {number} port Port to listen on.
* @returns {{port: number, state: {requests: Array<{cep: string, userAgent: string}>}, reset: () => void, stop: () => void}}
*/
export function startFakeApi(port) {
const state = { requests: [] };
const server = Bun.serve({
port,
hostname: "0.0.0.0",
fetch(request) {
const cep = new URL(request.url).pathname.slice(1);
state.requests.push({ cep, userAgent: request.headers.get("user-agent") || "" });
if (!/^\d{8}$/.test(cep)) {
return new Response(
JSON.stringify({ erro: "cep_invalido", mensagem: "CEP deve ter 8 dígitos" }),
{ status: 400, headers: HEADERS },
);
}
const address = ADDRESSES[cep];
if (!address) {
return new Response(
JSON.stringify({ erro: "cep_nao_encontrado", mensagem: "CEP não existe na base do DNE" }),
{ status: 404, headers: HEADERS },
);
}
return new Response(JSON.stringify(address), { status: 200, headers: HEADERS });
},
});
return {
port: server.port,
state,
reset() {
state.requests.length = 0;
},
stop() {
server.stop(true);
},
};
}
if (import.meta.main) {
const api = startFakeApi(Number(process.argv[2] || 8899));
console.log(`fake cep.is on :${api.port}`);
}
|