Files
ContentGen_FE/src/lib/api/example/auth/service.ts
Harun CAN 8bd995ea18
Some checks failed
UI Deploy (Next-Auth Support) 🎨 / build-and-deploy (push) Has been cancelled
main
2026-03-30 00:22:06 +03:00

92 lines
2.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Auth Service — NextAuth CredentialsProvider için server-side auth çağrıları.
* `apiRequest` yerine doğrudan fetch kullanır (server-side, session gerektirmez).
*/
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/api';
interface LoginDto {
email: string;
password: string;
}
interface AuthUser {
id: string;
email: string;
firstName?: string;
lastName?: string;
roles?: string[];
}
interface AuthResponse {
accessToken: string;
refreshToken: string;
expiresIn?: number;
user: AuthUser;
}
interface ApiResponse<T> {
success: boolean;
data: T;
message?: string;
statusCode?: number;
}
async function authFetch<T>(url: string, body: unknown): Promise<ApiResponse<T>> {
try {
const res = await fetch(`${API_URL}${url}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const json = await res.json();
if (!res.ok) {
return {
success: false,
data: null as unknown as T,
message: json?.message || 'İstek başarısız',
statusCode: res.status,
};
}
return {
success: true,
data: json?.data ?? json,
message: json?.message,
statusCode: res.status,
};
} catch (error: unknown) {
const message = error instanceof Error ? error.message : 'Bağlantı hatası';
return {
success: false,
data: null as unknown as T,
message,
};
}
}
const login = (data: LoginDto) => {
return authFetch<AuthResponse>('/auth/login', data);
};
const register = (data: { email: string; password: string; firstName?: string; lastName?: string }) => {
return authFetch<AuthResponse>('/auth/register', data);
};
const refreshToken = (data: { refreshToken: string }) => {
return authFetch<AuthResponse>('/auth/refresh', data);
};
const logout = () => {
return authFetch<null>('/auth/logout', {});
};
export const authService = {
login,
register,
refreshToken,
logout,
};