@dijitrak/react-nextjs-seo-plugin
Version:
A modern, user-friendly SEO plugin for React and Next.js with multilingual support and comprehensive optimization tools
256 lines (232 loc) • 6.52 kB
text/typescript
/**
* API istemcisi işlemleri
* Meta veriler, şemalar ve diğer SEO bilgilerini almak ve güncellemek için API çağrıları
*/
import { SEOMetaData, JSONLDSchema, SEOScore, SEOIssue, ContentAnalysisResult } from '../types';
// API Taban URL'si
let apiBaseUrl = '';
/**
* API taban URL'sini ayarlar
*/
export function setApiBaseUrl(url: string) {
apiBaseUrl = url.endsWith('/') ? url : url + '/';
}
/**
* API isteği yapar
*/
async function apiRequest<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
// API URL'si ayarlanmadıysa hata fırlat
if (!apiBaseUrl) {
throw new Error('API base URL is not set. Use setApiBaseUrl first.');
}
const url = `${apiBaseUrl}${endpoint}`;
// Varsayılan options ayarları
const defaultOptions: RequestInit = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
};
// Options'ları birleştir
const requestOptions = {
...defaultOptions,
...options,
headers: {
...defaultOptions.headers,
...options.headers
}
};
try {
const response = await fetch(url, requestOptions);
// Yanıt başarılı değilse hata fırlat
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.message || `API request failed with status ${response.status}`);
}
// Yanıtı JSON olarak döndür
return await response.json();
} catch (error) {
console.error('API request error:', error);
throw error;
}
}
/**
* Sayfa meta verilerini getirir
*/
export async function fetchPageMeta(path: string): Promise<SEOMetaData> {
try {
return await apiRequest<SEOMetaData>(`meta?path=${encodeURIComponent(path)}`);
} catch (error) {
console.error('Error fetching page meta:', error);
throw error;
}
}
/**
* Sayfa meta verilerini günceller
*/
export async function updatePageMeta(path: string, metaData: Partial<SEOMetaData>): Promise<SEOMetaData> {
try {
return await apiRequest<SEOMetaData>(`meta?path=${encodeURIComponent(path)}`, {
method: 'PUT',
body: JSON.stringify(metaData)
});
} catch (error) {
console.error('Error updating page meta:', error);
throw error;
}
}
/**
* Sayfa JSON-LD şemalarını getirir
*/
export async function fetchJSONLDSchemas(path: string): Promise<JSONLDSchema[]> {
try {
return await apiRequest<JSONLDSchema[]>(`jsonld?path=${encodeURIComponent(path)}`);
} catch (error) {
console.error('Error fetching JSON-LD schemas:', error);
throw error;
}
}
/**
* Sayfa JSON-LD şemalarını günceller
*/
export async function updateJSONLDSchemas(path: string, schemas: JSONLDSchema[]): Promise<JSONLDSchema[]> {
try {
return await apiRequest<JSONLDSchema[]>(`jsonld?path=${encodeURIComponent(path)}`, {
method: 'PUT',
body: JSON.stringify(schemas)
});
} catch (error) {
console.error('Error updating JSON-LD schemas:', error);
throw error;
}
}
/**
* Sitemap.xml oluştur
*/
export async function generateSitemap(): Promise<string> {
try {
const response = await apiRequest<{ xml: string }>('sitemap/generate');
return response.xml;
} catch (error) {
console.error('Error generating sitemap:', error);
throw error;
}
}
/**
* Robots.txt oluştur
*/
export async function generateRobotsTxt(allowIndexing?: boolean, customRules?: string): Promise<string> {
try {
const params = new URLSearchParams();
if (allowIndexing !== undefined) {
params.append('allowIndexing', allowIndexing.toString());
}
if (customRules) {
params.append('customRules', customRules);
}
const queryString = params.toString() ? `?${params.toString()}` : '';
const response = await apiRequest<{ text: string }>(`robots/generate${queryString}`);
return response.text;
} catch (error) {
console.error('Error generating robots.txt:', error);
throw error;
}
}
/**
* SEO puanını getirir
*/
export async function fetchSEOScore(path: string): Promise<SEOScore> {
try {
return await apiRequest<SEOScore>(`score?path=${encodeURIComponent(path)}`);
} catch (error) {
console.error('Error fetching SEO score:', error);
throw error;
}
}
/**
* SEO sorunlarını getirir
*/
export async function fetchSEOIssues(path: string): Promise<SEOIssue[]> {
try {
return await apiRequest<SEOIssue[]>(`issues?path=${encodeURIComponent(path)}`);
} catch (error) {
console.error('Error fetching SEO issues:', error);
throw error;
}
}
/**
* SEO önerilerini getirir
*/
export async function fetchSEOTips(): Promise<Array<{
id: number;
title: string;
description: string;
category: string;
createdAt: string;
}>> {
try {
return await apiRequest<Array<{
id: number;
title: string;
description: string;
category: string;
createdAt: string;
}>>('tips');
} catch (error) {
console.error('Error fetching SEO tips:', error);
throw error;
}
}
/**
* İçerik analizi yapar
*/
export async function analyzeContent(content: string, keywords?: string): Promise<ContentAnalysisResult> {
try {
return await apiRequest<ContentAnalysisResult>('analyze/content', {
method: 'POST',
body: JSON.stringify({ content, keywords })
});
} catch (error) {
console.error('Error analyzing content:', error);
throw error;
}
}
/**
* Meta açıklama üretir
*/
export async function generateMetaDescription(content: string, maxLength: number = 160): Promise<string> {
try {
const response = await apiRequest<{ description: string }>('generate/meta-description', {
method: 'POST',
body: JSON.stringify({ content, maxLength })
});
return response.description;
} catch (error) {
console.error('Error generating meta description:', error);
throw error;
}
}
/**
* Sosyal medya önizleme görseli üretir
*/
export async function generateSocialPreviewImage(props: {
title: string;
subtitle?: string;
backgroundUrl?: string;
logoUrl?: string;
textColor?: string;
backgroundColor?: string;
width?: number;
height?: number;
}): Promise<{ url: string }> {
try {
const response = await apiRequest<{ url: string }>('generate/social-image', {
method: 'POST',
body: JSON.stringify(props)
});
return response;
} catch (error) {
console.error('Error generating social preview image:', error);
throw error;
}
}