fix: added interface that app.tsx uses
Some checks failed
Build and push Docker image / build (push) Failing after 4m0s
Release new version / release (push) Successful in 28s
Update changelog / changelog (push) Successful in 26s

This commit is contained in:
Pc
2026-01-06 16:50:42 +01:00
parent 6383916101
commit cc31de6c8d

View File

@@ -8,11 +8,18 @@ import {
// Pobieramy adres API // Pobieramy adres API
const API_BASE = import.meta.env.VITE_API_TARGET; const API_BASE = import.meta.env.VITE_API_TARGET;
// Nazwa klucza w localStorage, gdzie trzymasz token // Nazwa klucza w localStorage
const TOKEN_KEY = 'jwt_token'; const TOKEN_KEY = 'jwt_token';
type CaseType = 'upper' | 'lower' | 'mixed'; type CaseType = 'upper' | 'lower' | 'mixed';
// 1. Definicja propsów, które przychodzą z App.tsx
interface GeneratorProps {
url: string;
setUrl: (url: string) => void;
onGenerate: () => void;
}
interface GeneratorSettings { interface GeneratorSettings {
length: number; length: number;
alphanum: boolean; alphanum: boolean;
@@ -20,8 +27,8 @@ interface GeneratorSettings {
withSubdomain: boolean; withSubdomain: boolean;
} }
// Usunęliśmy 'remoteUrl' stąd, bo teraz przychodzi z propsów (url)
interface LinkFormData { interface LinkFormData {
remoteUrl: string;
uri: string; uri: string;
subdomain: string; subdomain: string;
privacy: boolean; privacy: boolean;
@@ -39,23 +46,22 @@ interface LinkPayload {
interface User { interface User {
id: string; id: string;
username: string; username: string;
email?: string; email?: string;
} }
export const Generator: React.FC = () => { // 2. Dodajemy propsy do argumentów funkcji
export const Generator: React.FC<GeneratorProps> = ({ url, setUrl, onGenerate }) => {
const [user, setUser] = useState<User | null>(null); const [user, setUser] = useState<User | null>(null);
// Stan formularza głównego // Stan formularza (bez remoteUrl, bo to jest teraz w 'url')
const [formData, setFormData] = useState<LinkFormData>({ const [formData, setFormData] = useState<LinkFormData>({
remoteUrl: '',
uri: '', uri: '',
subdomain: '', subdomain: '',
privacy: true, privacy: true,
expiryDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0] expiryDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
}); });
// Stan ustawień generatora (GET)
const [genSettings, setGenSettings] = useState<GeneratorSettings>({ const [genSettings, setGenSettings] = useState<GeneratorSettings>({
length: 6, length: 6,
alphanum: true, alphanum: true,
@@ -63,14 +69,12 @@ export const Generator: React.FC = () => {
withSubdomain: false withSubdomain: false
}); });
// Stany UI
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [generatingUri, setGeneratingUri] = useState(false); const [generatingUri, setGeneratingUri] = useState(false);
const [errorMsg, setErrorMsg] = useState<string | null>(null); const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [result, setResult] = useState<string | null>(null); const [result, setResult] = useState<string | null>(null);
const [copied, setCopied] = useState(false); const [copied, setCopied] = useState(false);
// Helper do pobierania nagłówków z tokenem
const getAuthHeaders = () => { const getAuthHeaders = () => {
const token = localStorage.getItem(TOKEN_KEY); const token = localStorage.getItem(TOKEN_KEY);
return { return {
@@ -79,13 +83,10 @@ export const Generator: React.FC = () => {
}; };
}; };
// 1. Sprawdzenie sesji użytkownika przy starcie (używając JWT) // Sprawdzenie sesji użytkownika
// 1. Sprawdzenie sesji użytkownika przy starcie
useEffect(() => { useEffect(() => {
const checkUser = async () => { const checkUser = async () => {
const token = localStorage.getItem(TOKEN_KEY); const token = localStorage.getItem(TOKEN_KEY);
// Jeśli brak tokena, przerywamy (tryb gościa)
if (!token) return; if (!token) return;
try { try {
@@ -95,30 +96,23 @@ export const Generator: React.FC = () => {
if (res.ok) { if (res.ok) {
const data = await res.json(); const data = await res.json();
// Naprawa "Logged in as undefined":
// API może zwracać 'name', 'username' lub tylko 'email'
setUser({ setUser({
id: data.id || data._id || data.userId, id: data.id || data._id || data.userId,
username: data.username || data.name || data.email || "User", username: data.username || data.name || data.email || "User",
email: data.email email: data.email
}); });
} else { } else {
// Jeśli token jest nieważny (401), czyścimy go
console.log("Session expired. Logging out."); console.log("Session expired. Logging out.");
localStorage.removeItem(TOKEN_KEY); localStorage.removeItem(TOKEN_KEY);
setUser(null); setUser(null);
} }
} catch { } catch {
// POPRAWKA: Usunęliśmy '(err)', teraz jest samo 'catch'
// Dzięki temu linter nie krzyczy o nieużywaną zmienną
console.log("API unreachable"); console.log("API unreachable");
} }
}; };
checkUser(); checkUser();
}, []); }, []);
// 2. Generowanie URI (GET) - tutaj auth zazwyczaj nie jest wymagany, ale można dodać
const handleGenerateUri = async (type: 'random' | 'wordlist') => { const handleGenerateUri = async (type: 'random' | 'wordlist') => {
setGeneratingUri(true); setGeneratingUri(true);
setErrorMsg(null); setErrorMsg(null);
@@ -140,8 +134,6 @@ export const Generator: React.FC = () => {
endpoint = '/api/v1/link/fromWordlist'; endpoint = '/api/v1/link/fromWordlist';
} }
// GET zazwyczaj jest publiczny, więc nie musimy dodawać Bearera,
// ale jeśli API tego wymaga, dodaj: headers: getAuthHeaders()
const response = await fetch(`${API_BASE}${endpoint}?${params.toString()}`); const response = await fetch(`${API_BASE}${endpoint}?${params.toString()}`);
const data = await response.json(); const data = await response.json();
@@ -157,9 +149,9 @@ export const Generator: React.FC = () => {
} }
}; };
// 3. Zapis do bazy (POST) - WYMAGA AUTH (JWT)
const handleSubmitToDb = async () => { const handleSubmitToDb = async () => {
if (!formData.remoteUrl) { // Używamy propsa 'url' zamiast formData.remoteUrl
if (!url) {
setErrorMsg("Meow! I need a destination URL first! 🐾"); setErrorMsg("Meow! I need a destination URL first! 🐾");
return; return;
} }
@@ -174,7 +166,7 @@ export const Generator: React.FC = () => {
try { try {
const payload: LinkPayload = { const payload: LinkPayload = {
remoteUrl: formData.remoteUrl, remoteUrl: url, // <-- Tutaj wstawiamy wartość z propsa
uri: formData.uri, uri: formData.uri,
subdomain: formData.subdomain || undefined, subdomain: formData.subdomain || undefined,
privacy: formData.privacy, privacy: formData.privacy,
@@ -187,7 +179,7 @@ export const Generator: React.FC = () => {
const response = await fetch(`${API_BASE}/api/v1/link/new`, { const response = await fetch(`${API_BASE}/api/v1/link/new`, {
method: 'POST', method: 'POST',
headers: getAuthHeaders(), // Tu wstrzykujemy JWT headers: getAuthHeaders(),
body: JSON.stringify(payload) body: JSON.stringify(payload)
}); });
@@ -200,6 +192,9 @@ export const Generator: React.FC = () => {
const finalLink = data.url || `${API_BASE.replace('api.', '')}/${formData.uri}`; const finalLink = data.url || `${API_BASE.replace('api.', '')}/${formData.uri}`;
setResult(finalLink); setResult(finalLink);
// Wywołujemy callback z App.tsx (np. żeby pokazać powiadomienie)
onGenerate();
} catch (err: unknown) { } catch (err: unknown) {
if (err instanceof Error) setErrorMsg(err.message); if (err instanceof Error) setErrorMsg(err.message);
else setErrorMsg("Something went wrong saving to DB!"); else setErrorMsg("Something went wrong saving to DB!");
@@ -227,7 +222,6 @@ export const Generator: React.FC = () => {
KittyURL <PawPrint className="w-8 h-8 sm:w-10 sm:h-10" fill="currentColor" /> KittyURL <PawPrint className="w-8 h-8 sm:w-10 sm:h-10" fill="currentColor" />
</h1> </h1>
<p className="text-pink-300 font-medium">Shorten your links with a purr!</p> <p className="text-pink-300 font-medium">Shorten your links with a purr!</p>
</header> </header>
{/* Error Display */} {/* Error Display */}
@@ -277,8 +271,8 @@ export const Generator: React.FC = () => {
type="url" type="url"
placeholder="https://very-long-link.com/..." placeholder="https://very-long-link.com/..."
className="w-full p-4 bg-pink-50/30 border-2 border-pink-100 rounded-2xl outline-none focus:border-pink-400 focus:bg-white transition-all text-pink-600 font-medium pr-12" className="w-full p-4 bg-pink-50/30 border-2 border-pink-100 rounded-2xl outline-none focus:border-pink-400 focus:bg-white transition-all text-pink-600 font-medium pr-12"
value={formData.remoteUrl} value={url} // Używamy propsa
onChange={(e) => setFormData({ ...formData, remoteUrl: e.target.value })} onChange={(e) => setUrl(e.target.value)} // Używamy propsa
/> />
<Heart className="absolute right-4 top-1/2 -translate-y-1/2 text-pink-200 w-5 h-5 group-focus-within:text-pink-400 transition-colors" /> <Heart className="absolute right-4 top-1/2 -translate-y-1/2 text-pink-200 w-5 h-5 group-focus-within:text-pink-400 transition-colors" />
</div> </div>