Template
Modelo do encurtador em Next.js
Gerado a partir de deploy-templates/nextjs (dado.cloud 4c2a882).
This commit is contained in:
@@ -0,0 +1,7 @@
|
|||||||
|
node_modules/
|
||||||
|
.next/
|
||||||
|
out/
|
||||||
|
next-env.d.ts
|
||||||
|
*.tsbuildinfo
|
||||||
|
.env*
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
# Encurtador de links em Next.js
|
||||||
|
|
||||||
|
Um encurtador de links pronto para publicar na [Dado](https://dado.cloud): cole um link
|
||||||
|
comprido, receba um endereço curto e acompanhe quantas vezes ele foi aberto.
|
||||||
|
|
||||||
|
Este repositório nasceu de um modelo da Dado. Cada `git push` na branch `main` publica
|
||||||
|
uma versão nova do seu app, sozinho.
|
||||||
|
|
||||||
|
## O que tem aqui
|
||||||
|
|
||||||
|
- `app/page.tsx`: a página (formulário, últimos links e "Sobre este deploy").
|
||||||
|
- `app/Encurtador.tsx`: a parte interativa da página (encurtar, copiar, lista).
|
||||||
|
- `app/api/links/route.ts`: a API — `POST /api/links` cria, `GET /api/links` lista.
|
||||||
|
- `app/[codigo]/route.ts`: o redirecionamento `GET /<código>` (302) e a contagem de cliques.
|
||||||
|
- `lib/links.ts`: onde os links ficam guardados (na memória).
|
||||||
|
- `app/globals.css`: o visual. Mude à vontade.
|
||||||
|
|
||||||
|
Não tem banco de dados: os links ficam na memória do app e **somem quando ele é publicado
|
||||||
|
de novo**. Veja no fim como guardar de vez.
|
||||||
|
|
||||||
|
## Rodar no seu computador
|
||||||
|
|
||||||
|
Precisa de Node.js 20.9 ou mais novo.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://git.dado.cloud/<sua-conta>/encurtador-nextjs.git
|
||||||
|
cd encurtador-nextjs
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Abra http://localhost:3000.
|
||||||
|
|
||||||
|
Quando o `git clone` pedir usuário e senha, use o usuário da sua conta de Repositórios e,
|
||||||
|
como senha, o **token de Repositórios** (no painel da Dado, em Repositórios). O comando
|
||||||
|
certinho do seu app aparece no painel, em Deploys, na visão geral do app.
|
||||||
|
|
||||||
|
## Mudar e publicar
|
||||||
|
|
||||||
|
Edite o que quiser e mande para a Dado:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add .
|
||||||
|
git commit -m "Minha primeira mudança"
|
||||||
|
git push
|
||||||
|
```
|
||||||
|
|
||||||
|
O push na branch `main` publica uma versão nova. Dá para acompanhar o andamento em
|
||||||
|
Deploys, no painel.
|
||||||
|
|
||||||
|
## Variável de ambiente de exemplo
|
||||||
|
|
||||||
|
A mensagem em "Sobre este deploy" vem da variável `MENSAGEM_BOAS_VINDAS`. Para trocar,
|
||||||
|
abra Deploys no painel, clique em "Variáveis de ambiente" no seu app, salve e publique de
|
||||||
|
novo. No seu computador:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
MENSAGEM_BOAS_VINDAS="Oi, mundo" npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Encurtar
|
||||||
|
curl -X POST https://<endereço-do-seu-app>/api/links \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{"url": "https://exemplo.com.br/uma-pagina"}'
|
||||||
|
# 201 {"codigo":"a1b2c3","url":"https://exemplo.com.br/uma-pagina","curto":"https://<endereço-do-seu-app>/a1b2c3","cliques":0,"criadoEm":"..."}
|
||||||
|
|
||||||
|
# Últimos 20 links
|
||||||
|
curl https://<endereço-do-seu-app>/api/links
|
||||||
|
# 200 {"links":[...]}
|
||||||
|
```
|
||||||
|
|
||||||
|
`GET /<código>` redireciona (302) para o link original e soma um clique. A API aceita
|
||||||
|
chamadas de qualquer site (CORS aberto só em `/api/*`), então outro app seu pode usá-la.
|
||||||
|
Para evitar abuso, cada IP cria no máximo 30 links a cada 10 minutos.
|
||||||
|
|
||||||
|
## Guardar os links de vez
|
||||||
|
|
||||||
|
Para os links sobreviverem a uma nova publicação, ligue um Postgres no app (painel, em
|
||||||
|
Deploys, aba "Banco de dados" do app). A conexão chega ao app na variável `DATABASE_URL`;
|
||||||
|
aí é trocar o que está em `lib/links.ts` por consultas ao banco.
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
import type { LinkJson } from '@/lib/links';
|
||||||
|
|
||||||
|
const semProtocolo = (url: string) => url.replace(/^https?:\/\//, '');
|
||||||
|
|
||||||
|
export default function Encurtador({ linksIniciais }: { linksIniciais: LinkJson[] }) {
|
||||||
|
const [url, setUrl] = useState('');
|
||||||
|
const [enviando, setEnviando] = useState(false);
|
||||||
|
const [erro, setErro] = useState<string | null>(null);
|
||||||
|
const [criado, setCriado] = useState<LinkJson | null>(null);
|
||||||
|
const [copiado, setCopiado] = useState(false);
|
||||||
|
const [links, setLinks] = useState(linksIniciais);
|
||||||
|
|
||||||
|
const carregarLinks = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const resposta = await fetch('/api/links', { cache: 'no-store' });
|
||||||
|
if (resposta.ok) setLinks(((await resposta.json()) as { links: LinkJson[] }).links);
|
||||||
|
} catch {
|
||||||
|
// Sem rede: a lista fica como estava.
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Voltou para a aba depois de testar um link? Atualiza a contagem de cliques.
|
||||||
|
useEffect(() => {
|
||||||
|
const aoVoltar = () => {
|
||||||
|
if (document.visibilityState === 'visible') void carregarLinks();
|
||||||
|
};
|
||||||
|
document.addEventListener('visibilitychange', aoVoltar);
|
||||||
|
return () => document.removeEventListener('visibilitychange', aoVoltar);
|
||||||
|
}, [carregarLinks]);
|
||||||
|
|
||||||
|
async function encurtar(evento: React.FormEvent<HTMLFormElement>) {
|
||||||
|
evento.preventDefault();
|
||||||
|
setErro(null);
|
||||||
|
let alvo = url.trim();
|
||||||
|
if (!alvo) return setErro('Cole um link para encurtar.');
|
||||||
|
// Quem digita "exemplo.com.br" quer dizer https://exemplo.com.br.
|
||||||
|
if (!/^[a-z][a-z0-9+.-]*:/i.test(alvo)) alvo = `https://${alvo}`;
|
||||||
|
|
||||||
|
setEnviando(true);
|
||||||
|
try {
|
||||||
|
const resposta = await fetch('/api/links', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ url: alvo }),
|
||||||
|
});
|
||||||
|
const dados = await resposta.json().catch(() => ({}));
|
||||||
|
if (!resposta.ok) return setErro(dados.erro || 'Não deu para encurtar esse link. Tente de novo.');
|
||||||
|
setCriado(dados as LinkJson);
|
||||||
|
setCopiado(false);
|
||||||
|
setUrl('');
|
||||||
|
await carregarLinks();
|
||||||
|
} catch {
|
||||||
|
setErro('Sem conexão com o servidor. Tente de novo.');
|
||||||
|
} finally {
|
||||||
|
setEnviando(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copiar() {
|
||||||
|
if (!criado) return;
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(criado.curto);
|
||||||
|
setCopiado(true);
|
||||||
|
} catch {
|
||||||
|
// Navegador sem permissão de área de transferência: seleciona o link.
|
||||||
|
const alvo = document.getElementById('curto');
|
||||||
|
if (alvo) getSelection()?.selectAllChildren(alvo);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<section className="cartao">
|
||||||
|
<form className="formulario" onSubmit={encurtar} noValidate>
|
||||||
|
<label htmlFor="url" className="so-leitor">
|
||||||
|
Link para encurtar
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="url"
|
||||||
|
name="url"
|
||||||
|
type="url"
|
||||||
|
inputMode="url"
|
||||||
|
maxLength={2048}
|
||||||
|
placeholder="Cole seu link aqui"
|
||||||
|
autoComplete="off"
|
||||||
|
required
|
||||||
|
value={url}
|
||||||
|
onChange={(e) => setUrl(e.target.value)}
|
||||||
|
/>
|
||||||
|
<button type="submit" disabled={enviando}>
|
||||||
|
Encurtar
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
{erro && (
|
||||||
|
<p className="erro" role="alert">
|
||||||
|
{erro}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{criado && (
|
||||||
|
<div className="resultado">
|
||||||
|
<a id="curto" href={criado.curto} target="_blank" rel="noopener">
|
||||||
|
{semProtocolo(criado.curto)}
|
||||||
|
</a>
|
||||||
|
<button type="button" className="secundario" onClick={copiar}>
|
||||||
|
{copiado ? 'Copiado!' : 'Copiar'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<h2>Últimos links</h2>
|
||||||
|
<section className="cartao">
|
||||||
|
{links.length === 0 ? (
|
||||||
|
<p className="vazio">Nenhum link ainda. Encurte o primeiro aí em cima.</p>
|
||||||
|
) : (
|
||||||
|
<ul className="lista">
|
||||||
|
{links.map((link) => (
|
||||||
|
<li key={link.codigo}>
|
||||||
|
<div className="link-info">
|
||||||
|
<a href={link.curto} target="_blank" rel="noopener">
|
||||||
|
{semProtocolo(link.curto)}
|
||||||
|
</a>
|
||||||
|
<span className="destino" title={link.url}>
|
||||||
|
{link.url}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span className="cliques">{link.cliques === 1 ? '1 clique' : `${link.cliques} cliques`}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { FORMATO_CODIGO, registrarClique } from '@/lib/links';
|
||||||
|
|
||||||
|
// O redirecionamento é feito pelo servidor: GET /<código> → 302 para o link.
|
||||||
|
export async function GET(_request: Request, { params }: { params: Promise<{ codigo: string }> }) {
|
||||||
|
const { codigo } = await params;
|
||||||
|
const link = FORMATO_CODIGO.test(codigo) ? registrarClique(codigo) : null;
|
||||||
|
if (!link) {
|
||||||
|
return new Response(PAGINA_NAO_ENCONTRADA, {
|
||||||
|
status: 404,
|
||||||
|
headers: { 'Content-Type': 'text/html; charset=utf-8' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return new Response(null, { status: 302, headers: { Location: link.url, 'Cache-Control': 'no-store' } });
|
||||||
|
}
|
||||||
|
|
||||||
|
const PAGINA_NAO_ENCONTRADA = `<!doctype html>
|
||||||
|
<html lang="pt-BR">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>Link não encontrado</title>
|
||||||
|
<style>
|
||||||
|
:root { color-scheme: light dark; }
|
||||||
|
body {
|
||||||
|
margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 16px;
|
||||||
|
font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||||
|
background: #f6f7f9; color: #14161a; line-height: 1.5;
|
||||||
|
}
|
||||||
|
main { max-width: 420px; text-align: center; }
|
||||||
|
h1 { font-size: 24px; margin: 0 0 8px; }
|
||||||
|
p { color: #5b6270; margin: 0 0 20px; }
|
||||||
|
a { color: #3b5bdb; font-weight: 600; }
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
body { background: #0f1115; color: #eceef2; }
|
||||||
|
p { color: #9aa1ad; }
|
||||||
|
a { color: #8299ff; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main>
|
||||||
|
<h1>Link não encontrado</h1>
|
||||||
|
<p>Esse link curto não existe ou sumiu quando o app foi publicado de novo.</p>
|
||||||
|
<a href="/">Encurtar um link</a>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
`;
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { criarLink, enderecoBase, ErroDeValidacao, listarLinks, paraJson } from '@/lib/links';
|
||||||
|
|
||||||
|
// CORS aberto só na API: qualquer site (ou outro app seu) pode chamar /api/*.
|
||||||
|
const CORS = {
|
||||||
|
'Access-Control-Allow-Origin': '*',
|
||||||
|
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
||||||
|
'Access-Control-Allow-Headers': 'Content-Type',
|
||||||
|
};
|
||||||
|
|
||||||
|
// Freio simples contra abuso: no máximo 30 links novos a cada 10 minutos por IP.
|
||||||
|
const LIMITE_POR_IP = 30;
|
||||||
|
const JANELA_MS = 10 * 60 * 1000;
|
||||||
|
const tentativas = new Map<string, { total: number; expiraEm: number }>();
|
||||||
|
|
||||||
|
function passouDoLimite(ip: string): boolean {
|
||||||
|
const agora = Date.now();
|
||||||
|
if (tentativas.size > 10_000) tentativas.clear();
|
||||||
|
const atual = tentativas.get(ip);
|
||||||
|
if (!atual || atual.expiraEm <= agora) {
|
||||||
|
tentativas.set(ip, { total: 1, expiraEm: agora + JANELA_MS });
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
atual.total += 1;
|
||||||
|
return atual.total > LIMITE_POR_IP;
|
||||||
|
}
|
||||||
|
|
||||||
|
const erro = (status: number, mensagem: string) => Response.json({ erro: mensagem }, { status, headers: CORS });
|
||||||
|
|
||||||
|
export function OPTIONS() {
|
||||||
|
return new Response(null, { status: 204, headers: CORS });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function GET(request: Request) {
|
||||||
|
const base = enderecoBase(request.headers);
|
||||||
|
return Response.json(
|
||||||
|
{ links: listarLinks().map((link) => paraJson(link, base)) },
|
||||||
|
{ headers: { ...CORS, 'Cache-Control': 'no-store' } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const ip = request.headers.get('cf-connecting-ip') ?? request.headers.get('x-forwarded-for')?.split(',')[0].trim() ?? '?';
|
||||||
|
if (passouDoLimite(ip)) return erro(429, 'Muitos links em pouco tempo. Espere alguns minutos e tente de novo.');
|
||||||
|
|
||||||
|
let corpo: { url?: unknown } | null;
|
||||||
|
try {
|
||||||
|
corpo = await request.json();
|
||||||
|
} catch {
|
||||||
|
return erro(400, 'Corpo inválido. Envie JSON no formato {"url": "https://..."}.');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const link = criarLink(corpo?.url);
|
||||||
|
return Response.json(paraJson(link, enderecoBase(request.headers)), { status: 201, headers: CORS });
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof ErroDeValidacao) return erro(400, e.message);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
+107
@@ -0,0 +1,107 @@
|
|||||||
|
/* Mesmo visual nos modelos Next.js, Express e FastAPI. Mude à vontade. */
|
||||||
|
:root {
|
||||||
|
--fundo: #f6f7f9;
|
||||||
|
--cartao: #ffffff;
|
||||||
|
--texto: #14161a;
|
||||||
|
--suave: #5b6270;
|
||||||
|
--borda: #e3e6eb;
|
||||||
|
--destaque: #3b5bdb;
|
||||||
|
--destaque-texto: #ffffff;
|
||||||
|
--destaque-suave: #edf1ff;
|
||||||
|
--erro: #c92a2a;
|
||||||
|
--raio: 14px;
|
||||||
|
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
|
||||||
|
color-scheme: light dark;
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root {
|
||||||
|
--fundo: #0f1115;
|
||||||
|
--cartao: #171a21;
|
||||||
|
--texto: #eceef2;
|
||||||
|
--suave: #9aa1ad;
|
||||||
|
--borda: #2a2f3a;
|
||||||
|
--destaque: #8299ff;
|
||||||
|
--destaque-texto: #0f1115;
|
||||||
|
--destaque-suave: #1e2540;
|
||||||
|
--erro: #ff8787;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||||
|
background: var(--fundo);
|
||||||
|
color: var(--texto);
|
||||||
|
line-height: 1.5;
|
||||||
|
-webkit-text-size-adjust: 100%;
|
||||||
|
}
|
||||||
|
.pagina { max-width: 640px; margin: 0 auto; padding: 56px 16px 32px; }
|
||||||
|
.topo { display: flex; align-items: center; gap: 12px; margin-bottom: 8px; }
|
||||||
|
.marca {
|
||||||
|
flex: none; width: 40px; height: 40px; border-radius: 10px;
|
||||||
|
background: var(--destaque); color: var(--destaque-texto);
|
||||||
|
display: grid; place-items: center;
|
||||||
|
}
|
||||||
|
h1 { font-size: 28px; line-height: 1.2; margin: 0; letter-spacing: -0.02em; }
|
||||||
|
h2 { font-size: 16px; margin: 32px 0 12px; }
|
||||||
|
.lead { color: var(--suave); margin: 0 0 24px; }
|
||||||
|
.cartao { background: var(--cartao); border: 1px solid var(--borda); border-radius: var(--raio); padding: 20px; }
|
||||||
|
.formulario { display: flex; gap: 8px; }
|
||||||
|
.formulario input {
|
||||||
|
flex: 1; min-width: 0; font: inherit; padding: 12px 14px;
|
||||||
|
border: 1px solid var(--borda); border-radius: 10px;
|
||||||
|
background: var(--fundo); color: var(--texto);
|
||||||
|
}
|
||||||
|
.formulario input:focus { outline: 2px solid var(--destaque); outline-offset: 1px; }
|
||||||
|
button {
|
||||||
|
font: inherit; font-weight: 600; padding: 12px 20px; border: 0; border-radius: 10px;
|
||||||
|
background: var(--destaque); color: var(--destaque-texto); cursor: pointer; white-space: nowrap;
|
||||||
|
}
|
||||||
|
button:disabled { opacity: 0.6; cursor: progress; }
|
||||||
|
button:focus-visible, a:focus-visible { outline: 2px solid var(--destaque); outline-offset: 2px; }
|
||||||
|
.secundario { background: var(--cartao); color: var(--destaque); border: 1px solid var(--borda); padding: 8px 14px; }
|
||||||
|
.erro { color: var(--erro); margin: 10px 0 0; font-size: 14px; }
|
||||||
|
.resultado {
|
||||||
|
margin-top: 16px; display: flex; align-items: center; gap: 12px;
|
||||||
|
padding: 12px 14px; border-radius: 10px; background: var(--destaque-suave);
|
||||||
|
}
|
||||||
|
.resultado a {
|
||||||
|
flex: 1; min-width: 0; font-family: var(--mono); font-weight: 600;
|
||||||
|
color: var(--destaque); text-decoration: none; overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.lista { list-style: none; margin: 0; padding: 0; }
|
||||||
|
.lista li { display: flex; align-items: center; gap: 12px; padding: 12px 0; border-top: 1px solid var(--borda); }
|
||||||
|
.lista li:first-child { border-top: 0; padding-top: 0; }
|
||||||
|
.lista li:last-child { padding-bottom: 0; }
|
||||||
|
.link-info { flex: 1; min-width: 0; }
|
||||||
|
.link-info a { font-family: var(--mono); font-weight: 600; color: var(--texto); text-decoration: none; overflow-wrap: anywhere; }
|
||||||
|
.link-info a:hover { color: var(--destaque); }
|
||||||
|
.destino { display: block; color: var(--suave); font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.cliques { font-family: var(--mono); font-size: 14px; color: var(--suave); white-space: nowrap; }
|
||||||
|
.vazio { color: var(--suave); margin: 0; }
|
||||||
|
.aviso {
|
||||||
|
margin: 16px 0 0; font-size: 14px; color: var(--suave);
|
||||||
|
border: 1px dashed var(--borda); border-radius: var(--raio); padding: 14px 16px;
|
||||||
|
}
|
||||||
|
.aviso a { color: var(--destaque); font-weight: 600; }
|
||||||
|
.sobre { margin-top: 32px; }
|
||||||
|
.sobre h2 { margin-top: 0; }
|
||||||
|
.sobre dl { display: grid; grid-template-columns: max-content 1fr; gap: 6px 16px; margin: 0; font-size: 14px; }
|
||||||
|
.sobre dt { color: var(--suave); }
|
||||||
|
.sobre dd { margin: 0; overflow-wrap: anywhere; }
|
||||||
|
.dica { font-size: 13px; color: var(--suave); margin: 14px 0 0; }
|
||||||
|
code { font-family: var(--mono); font-size: 0.92em; }
|
||||||
|
.rodape { margin-top: 32px; text-align: center; font-size: 13px; color: var(--suave); }
|
||||||
|
.rodape a { color: inherit; }
|
||||||
|
.so-leitor {
|
||||||
|
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||||
|
overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0;
|
||||||
|
}
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.pagina { padding-top: 32px; }
|
||||||
|
h1 { font-size: 24px; }
|
||||||
|
.formulario { flex-direction: column; }
|
||||||
|
.resultado { flex-direction: column; align-items: stretch; }
|
||||||
|
.sobre dl { grid-template-columns: 1fr; gap: 0; }
|
||||||
|
.sobre dd { margin-bottom: 8px; }
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="8" fill="#3b5bdb"/><path d="M13.5 18.5l5-5M12 15l-2 2a3.5 3.5 0 005 5l2-2M20 17l2-2a3.5 3.5 0 00-5-5l-2 2" stroke="white" stroke-width="2.2" fill="none" stroke-linecap="round"/></svg>
|
||||||
|
After Width: | Height: | Size: 277 B |
@@ -0,0 +1,16 @@
|
|||||||
|
import type { Metadata } from 'next';
|
||||||
|
|
||||||
|
import './globals.css';
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: 'Encurtador de links',
|
||||||
|
description: 'Encurte links e acompanhe quantas vezes cada um foi aberto.',
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<html lang="pt-BR">
|
||||||
|
<body>{children}</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import { headers } from 'next/headers';
|
||||||
|
|
||||||
|
import { enderecoBase, listarLinks, paraJson } from '@/lib/links';
|
||||||
|
|
||||||
|
import pacote from '../package.json';
|
||||||
|
import Encurtador from './Encurtador';
|
||||||
|
|
||||||
|
// A página lê os links e as variáveis a cada visita (nada de HTML congelado no build).
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
// Variável de ambiente de exemplo: na Dado, ela se configura no painel do app.
|
||||||
|
const MENSAGEM = process.env.MENSAGEM_BOAS_VINDAS || 'Defina a variável MENSAGEM_BOAS_VINDAS para trocar este texto.';
|
||||||
|
// Hora em que o processo do servidor subiu (= a publicação mais recente).
|
||||||
|
const INICIO = new Date(Date.now() - process.uptime() * 1000);
|
||||||
|
const fusoBrasilia = { timeZone: 'America/Sao_Paulo' } as const;
|
||||||
|
const INICIO_FORMATADO = `${INICIO.toLocaleDateString('pt-BR', fusoBrasilia)} às ${INICIO.toLocaleTimeString('pt-BR', {
|
||||||
|
...fusoBrasilia,
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
})} (horário de Brasília)`;
|
||||||
|
|
||||||
|
export default async function Pagina() {
|
||||||
|
const base = enderecoBase(await headers());
|
||||||
|
const linksIniciais = listarLinks().map((link) => paraJson(link, base));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="pagina">
|
||||||
|
<header className="topo">
|
||||||
|
<span className="marca" aria-hidden="true">
|
||||||
|
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round">
|
||||||
|
<path d="M10 14l4-4M8.5 11.5l-1.8 1.8a3.2 3.2 0 004.5 4.5l1.8-1.8M15.5 12.5l1.8-1.8a3.2 3.2 0 00-4.5-4.5l-1.8 1.8" />
|
||||||
|
</svg>
|
||||||
|
</span>
|
||||||
|
<h1>Encurtador de links</h1>
|
||||||
|
</header>
|
||||||
|
<p className="lead">Cole um link comprido e receba um endereço curto, pronto para compartilhar.</p>
|
||||||
|
|
||||||
|
<Encurtador linksIniciais={linksIniciais} />
|
||||||
|
|
||||||
|
<p className="aviso">
|
||||||
|
Os links ficam na memória do app e somem quando ele é publicado de novo. Para guardar os links de vez,{' '}
|
||||||
|
<a href="https://app.dado.cloud/deploys" target="_blank" rel="noopener">
|
||||||
|
ligue um Postgres
|
||||||
|
</a>
|
||||||
|
.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<section className="sobre cartao" aria-labelledby="sobre-titulo">
|
||||||
|
<h2 id="sobre-titulo">Sobre este deploy</h2>
|
||||||
|
<dl>
|
||||||
|
<dt>Runtime</dt>
|
||||||
|
<dd>{`Next.js ${pacote.dependencies.next} · Node.js ${process.versions.node}`}</dd>
|
||||||
|
<dt>Região</dt>
|
||||||
|
<dd>Rodando em São Paulo</dd>
|
||||||
|
<dt>No ar desde</dt>
|
||||||
|
<dd>
|
||||||
|
<time dateTime={INICIO.toISOString()}>{INICIO_FORMATADO}</time>
|
||||||
|
</dd>
|
||||||
|
<dt>Mensagem</dt>
|
||||||
|
<dd>{MENSAGEM}</dd>
|
||||||
|
</dl>
|
||||||
|
<p className="dica">
|
||||||
|
A mensagem vem da variável <code>MENSAGEM_BOAS_VINDAS</code>. Troque o valor nas configurações do app, no
|
||||||
|
painel, e publique de novo.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<footer className="rodape">
|
||||||
|
Publicado na{' '}
|
||||||
|
<a href="https://dado.cloud" target="_blank" rel="noopener">
|
||||||
|
Dado
|
||||||
|
</a>
|
||||||
|
</footer>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
+101
@@ -0,0 +1,101 @@
|
|||||||
|
import { randomInt } from 'node:crypto';
|
||||||
|
|
||||||
|
// Os links ficam num Map na memória do processo: simples e sem banco, mas
|
||||||
|
// somem toda vez que o app reinicia ou é publicado de novo. Para guardar de
|
||||||
|
// vez, troque este arquivo por consultas a um Postgres.
|
||||||
|
|
||||||
|
export interface Link {
|
||||||
|
codigo: string;
|
||||||
|
url: string;
|
||||||
|
cliques: number;
|
||||||
|
criadoEm: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** O que a API devolve: o link mais o endereço curto completo. */
|
||||||
|
export interface LinkJson extends Link {
|
||||||
|
curto: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ALFABETO = 'abcdefghijklmnopqrstuvwxyz0123456789';
|
||||||
|
const TAMANHO_CODIGO = 6;
|
||||||
|
const TAMANHO_MAXIMO_URL = 2048;
|
||||||
|
// Teto de links guardados: passou disso, o mais antigo sai (protege a memória).
|
||||||
|
const MAXIMO_DE_LINKS = 1000;
|
||||||
|
const LINKS_NA_LISTA = 20;
|
||||||
|
// Caminhos do próprio app que nunca podem virar código.
|
||||||
|
const RESERVADOS = new Set(['api']);
|
||||||
|
|
||||||
|
export const FORMATO_CODIGO = /^[a-z0-9]{6}$/;
|
||||||
|
|
||||||
|
// No Next.js, cada rota pode ser empacotada separada: guardar o Map no
|
||||||
|
// globalThis garante que a página, a API e o redirecionamento vejam os mesmos links.
|
||||||
|
const guarda = globalThis as typeof globalThis & { __links?: Map<string, Link> };
|
||||||
|
const links = (guarda.__links ??= new Map<string, Link>());
|
||||||
|
|
||||||
|
export class ErroDeValidacao extends Error {}
|
||||||
|
|
||||||
|
function gerarCodigo(): string {
|
||||||
|
for (;;) {
|
||||||
|
let codigo = '';
|
||||||
|
for (let i = 0; i < TAMANHO_CODIGO; i += 1) codigo += ALFABETO[randomInt(ALFABETO.length)];
|
||||||
|
if (!links.has(codigo) && !RESERVADOS.has(codigo)) return codigo;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validarUrl(valor: unknown): string {
|
||||||
|
if (typeof valor !== 'string' || valor.trim() === '') {
|
||||||
|
throw new ErroDeValidacao('Envie o campo "url" com o link que você quer encurtar.');
|
||||||
|
}
|
||||||
|
const texto = valor.trim();
|
||||||
|
if (texto.length > TAMANHO_MAXIMO_URL) {
|
||||||
|
throw new ErroDeValidacao(`Esse link é comprido demais (máximo de ${TAMANHO_MAXIMO_URL} caracteres).`);
|
||||||
|
}
|
||||||
|
let url: URL | null;
|
||||||
|
try {
|
||||||
|
url = new URL(texto);
|
||||||
|
} catch {
|
||||||
|
url = null;
|
||||||
|
}
|
||||||
|
if (!url || (url.protocol !== 'http:' && url.protocol !== 'https:')) {
|
||||||
|
throw new ErroDeValidacao('Esse não parece um link válido. Use um endereço que comece com http:// ou https://.');
|
||||||
|
}
|
||||||
|
return url.href;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function criarLink(valor: unknown): Link {
|
||||||
|
const url = validarUrl(valor);
|
||||||
|
const link: Link = { codigo: gerarCodigo(), url, cliques: 0, criadoEm: new Date().toISOString() };
|
||||||
|
links.set(link.codigo, link);
|
||||||
|
if (links.size > MAXIMO_DE_LINKS) links.delete(links.keys().next().value!);
|
||||||
|
return link;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Os últimos links criados, do mais novo para o mais antigo. */
|
||||||
|
export function listarLinks(): Link[] {
|
||||||
|
return [...links.values()].slice(-LINKS_NA_LISTA).reverse();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Soma um clique e devolve o link, ou null se o código não existe. */
|
||||||
|
export function registrarClique(codigo: string): Link | null {
|
||||||
|
const link = links.get(codigo);
|
||||||
|
if (!link) return null;
|
||||||
|
link.cliques += 1;
|
||||||
|
return link;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Endereço público do app, a partir dos cabeçalhos que o proxy HTTPS repassa. */
|
||||||
|
export function enderecoBase(cabecalhos: Headers): string {
|
||||||
|
const protocolo = (cabecalhos.get('x-forwarded-proto') ?? 'http').split(',')[0].trim();
|
||||||
|
const host = cabecalhos.get('x-forwarded-host') ?? cabecalhos.get('host') ?? 'localhost:3000';
|
||||||
|
return `${protocolo}://${host}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function paraJson(link: Link, base: string): LinkJson {
|
||||||
|
return {
|
||||||
|
codigo: link.codigo,
|
||||||
|
url: link.url,
|
||||||
|
curto: `${base}/${link.codigo}`,
|
||||||
|
cliques: link.cliques,
|
||||||
|
criadoEm: link.criadoEm,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import type { NextConfig } from 'next';
|
||||||
|
|
||||||
|
const nextConfig: NextConfig = {
|
||||||
|
poweredByHeader: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
export default nextConfig;
|
||||||
Generated
+1380
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"name": "encurtador-nextjs",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"private": true,
|
||||||
|
"description": "Encurtador de links em Next.js, pronto para publicar na Dado.",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "next dev",
|
||||||
|
"build": "next build",
|
||||||
|
"start": "next start"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20.9"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"next": "16.4.2",
|
||||||
|
"react": "19.3.1",
|
||||||
|
"react-dom": "19.3.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "22.20.5",
|
||||||
|
"@types/react": "19.3.0",
|
||||||
|
"@types/react-dom": "19.3.0",
|
||||||
|
"typescript": "7.0.2"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"lib": ["dom", "dom.iterable", "esnext"],
|
||||||
|
"allowJs": false,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"strict": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"module": "esnext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"incremental": true,
|
||||||
|
"plugins": [{ "name": "next" }],
|
||||||
|
"paths": { "@/*": ["./*"] }
|
||||||
|
},
|
||||||
|
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"],
|
||||||
|
"exclude": ["node_modules"]
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user