summaryrefslogtreecommitdiffstats
path: root/test/fake-api.js
blob: d787bf123a65242df0900279cb909551333e043d (plain)
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/**
 * 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",
  },
};

/**
 * The municipality a CEP that does not exist would have belonged to, keyed by
 * the CEP that provokes it.
 *
 * `25845000` is the real-world shape of the whole problem: Areal/RJ answers
 * from 25845-001 upwards and never at the `-000` a shopper reaches for. Any
 * other missing CEP — `99999999` — belongs to no municipality at all, and the
 * API then omits `faixa` entirely rather than sending it as null, which is what
 * the plugin's fallback path has to keep working against.
 */
const RANGES = {
  25845000: {
    localidade: "Areal",
    uf: "RJ",
    estado: "Rio de Janeiro",
    regiao: "Sudeste",
    ibge: "3300225",
    cep_ini: "25845001",
    cep_fim: "25849899",
    ceps: 118,
  },

  // A faixa with no municipality in it. The real API does not send this, and
  // the point of having it here is that the checkout must not care: an
  // unusable faixa has to end in exactly the message the plugin has always
  // shown, not in a broken sentence and not in a JavaScript error.
  25849000: {
    uf: "RJ",
    cep_ini: "25845001",
    cep_fim: "25849899",
  },
};

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) {
        const missing = { erro: "cep_nao_encontrado", mensagem: "CEP não existe na base do DNE" };

        if (RANGES[cep]) {
          missing.faixa = RANGES[cep];
        }

        return new Response(JSON.stringify(missing), { 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}`);
}