JavaScript Examples

Complete examples for using the yLnk API with JavaScript (Node.js or browser).

Setup

const API_KEY = 'your-api-key-here';
const BASE_URL = 'https://api.ylnk.cc/v2/external/client';

// Helper function for API requests
async function apiRequest(endpoint, options = {}) {
  const url = `${BASE_URL}${endpoint}`;
  const headers = {
    'X-API-Key': API_KEY,
    'Content-Type': 'application/json',
    ...options.headers
  };

  const response = await fetch(url, {
    ...options,
    headers
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'API request failed');
  }

  return response.json();
}
async function createShortLink(originalUrl, options = {}) {
  const response = await apiRequest('/short-links', {
    method: 'POST',
    body: JSON.stringify({
      originalUrl,
      title: options.title,
      customUrl: options.customUrl,
      category: options.category,
      categoryTitle: options.categoryTitle,
      categoryValue: options.categoryValue
    })
  });

  return response.data;
}

// Usage
const link = await createShortLink('https://example.com/very/long/url', {
  title: 'My Link',
  customUrl: 'my-link'
});
console.log('Created:', link.shortUrl);
async function updateShortLink(id, updates) {
  const response = await apiRequest(`/short-links/${id}`, {
    method: 'PUT',
    body: JSON.stringify({
      id,
      ...updates
    })
  });

  return response.data;
}

// Usage
const updated = await updateShortLink('abc123', {
  title: 'Updated Title',
  isActive: true
});
async function listShortLinks(filters = {}) {
  const params = new URLSearchParams({
    page: filters.page || 1,
    size: filters.size || 10,
    ...(filters.year && { year: filters.year }),
    ...(filters.month && { month: filters.month }),
    ...(filters.search && { search: filters.search }),
    ...(filters.status && { status: filters.status })
  });

  const response = await apiRequest(`/short-links?${params}`);
  return response.data;
}

// Usage
const links = await listShortLinks({
  page: 1,
  size: 20,
  search: 'example',
  status: 'active'
});
async function getShortLink(id) {
  const response = await apiRequest(`/short-links/${id}`);
  return response.data;
}

// Usage
const link = await getShortLink('abc123');

Get Analytics Details

async function getAnalyticsDetails(shortUrl) {
  const params = new URLSearchParams({ shortUrl });
  const response = await apiRequest(`/analytics/details?${params}`);
  return response.data;
}

// Usage
const details = await getAnalyticsDetails('abc123');
console.log('Total clicks:', details.visitCount);

Get Click Traffic

async function getClickTraffic(shortUrl) {
  const params = new URLSearchParams({ shortUrl });
  const response = await apiRequest(`/analytics/click-traffic-platforms?${params}`);
  return response.data;
}

// Usage
const traffic = await getClickTraffic('abc123');
console.log('Clicks by country:', traffic.clicksTraffic);
console.log('Top platforms:', traffic.topPlatforms);

Get Visit Logs

async function getVisitLogs(shortUrl, startDate, endDate, page = 1, pageSize = 10) {
  const params = new URLSearchParams({
    shortUrl,
    startDate,
    endDate,
    page: page.toString(),
    pageSize: pageSize.toString()
  });
  const response = await apiRequest(`/analytics/visit-logs?${params}`);
  return response.data;
}

// Usage
const logs = await getVisitLogs('abc123', '2024-01-01', '2024-01-31', 1, 20);
console.log('Total visits:', logs.totalElements);
logs.content.forEach(log => {
  console.log(`${log.countryName}: ${log.browserName} on ${log.osName}`);
});

Filter Visit Logs by UTM

async function filterVisitLogs(shortUrl, startDate, endDate, utmFilters = {}) {
  const params = new URLSearchParams({
    shortUrl,
    startDate,
    endDate,
    ...(utmFilters.utmSource && { utmSource: utmFilters.utmSource }),
    ...(utmFilters.utmMedium && { utmMedium: utmFilters.utmMedium }),
    ...(utmFilters.utmCampaign && { utmCampaign: utmFilters.utmCampaign })
  });
  const response = await apiRequest(`/analytics/filter-visit-logs?${params}`);
  return response.data; // Returns a number (count)
}

// Usage
const count = await filterVisitLogs('abc123', '2024-01-01', '2024-01-31', {
  utmSource: 'google',
  utmMedium: 'cpc',
  utmCampaign: 'summer-sale'
});
console.log('Matching visits:', count);