@tradly/platform-core
v1.0.23
Published
Utility package for Tradly - handles currency, country, configs, and langify
Readme
@tradly/platform-core
Utility package for Tradly platform - handles currency, country, configuration, and translation services with automatic authentication.
Installation
npm install @tradly/platform-coreQuick Start
import {
initializeAuth,
getCurrencies,
getCountries,
} from "@tradly/platform-core";
// Initialize the package with your domain and environment
initializeAuth("beauty.tradly.co", "production");
// Now you can use all utility functions
const currencies = await getCurrencies();
const countries = await getCountries();
console.log("Currencies:", currencies);
console.log("Countries:", countries);Initialization
Important: You must call initializeAuth() before using any utility
functions. This sets up the domain, environment, and base URL for all API calls.
import { initializeAuth } from "@tradly/platform-core";
// Initialize with domain and environment
initializeAuth("beauty.tradly.co", "production");
// Or with custom base URL
initializeAuth("beauty.tradly.co", "production", "https://api.custom.com");The utility package automatically uses the auth package's configuration, so you only need to initialize once.
Currency Service
Get All Currencies
import { getCurrencies } from "@tradly/platform-core";
const currencies = await getCurrencies();
// Returns array of currencies
currencies.forEach((currency) => {
console.log(currency.code, currency.symbol, currency.name);
});Get Currency by ID
import { getCurrency } from "@tradly/platform-core";
const currency = await getCurrency(2082);
if (currency) {
console.log("Currency:", currency.code, currency.symbol);
}Currency Interface:
interface Currency {
id: number;
code: string;
symbol: string;
name: string;
exchange_rate?: number;
format?: string;
decimal_point?: string;
thousand_separator?: string;
precision?: number;
default?: boolean;
active?: boolean;
}Country Service
Get All Countries
import { getCountries } from "@tradly/platform-core";
const countries = await getCountries();
// Returns array of countries
countries.forEach((country) => {
console.log(country.name, country.code, country.dial_code);
});Get Tenant Countries
import { getTenantCountries } from "@tradly/platform-core";
// Get countries specific to the tenant
const tenantCountries = await getTenantCountries();
console.log("Tenant countries:", tenantCountries);Get Country by ID
import { getCountry } from "@tradly/platform-core";
const country = await getCountry(1);
if (country) {
console.log("Country:", country.name, country.code);
}Country Interface:
interface Country {
id: number;
name: string;
code: string;
dial_code: string;
}Config Service
Get Configurations
import { getConfigs } from "@tradly/platform-core";
const configs = await getConfigs();
if (configs) {
console.log("Configurations:", configs);
// Access specific config
console.log("Payment config:", configs.payment);
}Get Secure Configurations
import { getGroupedSecureConfigList } from "@tradly/platform-core";
// Get secure configs by parameter groups
const secureConfigs = await getGroupedSecureConfigList("payment,stripe");
if (secureConfigs) {
console.log("Secure configs:", secureConfigs);
}Home Service
Get Home Feed
import { getHome } from "@tradly/platform-core";
const response = await getHome();
if (response.status && response.data) {
console.log("Home feed:", response.data);
// Response may include:
// - featured_listings
// - categories
// - banners
// - other home page data
}Note: The home feed endpoint requires authentication (PK key or auth key).
Langify Service (Translations)
Get Translations by Group Names
import { getTranslations } from "@tradly/platform-core";
// Get translations for multiple groups
const translations = await getTranslations(["common", "validation", "auth"]);
if (translations) {
console.log("Translations:", translations);
// Access specific translation
console.log("Welcome message:", translations.common?.welcome);
}Get Single Translation Group
import { getTranslationGroup } from "@tradly/platform-core";
// Get translations for a single group
const commonTranslations = await getTranslationGroup("common");
if (commonTranslations) {
console.log("Common translations:", commonTranslations);
}Advanced Usage
Custom Request Options
All service functions accept optional RequestOptions:
import { getCurrencies } from "@tradly/platform-core";
const currencies = await getCurrencies({
language: "en",
currency: "USD",
cache: true,
cacheKey: "my_currencies",
cacheTTL: 3600000, // 1 hour
});RequestOptions Interface:
interface RequestOptions {
headers?: Record<string, string>;
cache?: boolean;
cacheKey?: string;
cacheTTL?: number; // Time to live in milliseconds
checkAuth?: boolean; // Check if auth key is required (default: true)
language?: string; // Language code (e.g., "en", "ar")
currency?: string; // Currency code (e.g., "USD", "SAR")
}Disable Authentication Check
import { getCurrencies } from "@tradly/platform-core";
// Skip auth check for public endpoints
const currencies = await getCurrencies({
checkAuth: false,
});Caching
The package includes built-in caching to prevent duplicate API calls:
import { getCurrencies } from "@tradly/platform-core";
// First call - fetches from API
const currencies1 = await getCurrencies({
cache: true,
cacheKey: "currencies_list",
cacheTTL: 3600000, // Cache for 1 hour
});
// Second call - returns from cache (if within TTL)
const currencies2 = await getCurrencies({
cache: true,
cacheKey: "currencies_list",
});API Fetch Utilities
The package provides low-level fetch utilities that automatically handle authentication:
import { get, post, put, del } from "@tradly/platform-core";
// GET request (automatically includes auth key or PK key)
const response = await get("/v1/configs");
// POST request
const response = await post("/v1/data", {
key: "value",
});
// PUT request
const response = await put("/v1/data/123", {
key: "updated_value",
});
// DELETE request
const response = await del("/v1/data/123");Auth Utilities (Re-exported)
The utility package re-exports auth utilities for convenience:
import {
initializeAuth,
getAuthConfig,
getDomain,
getEnv,
getBaseUrl,
getAuthKey,
setAuthKey,
clearAuthKey,
getUUID,
setUUID,
} from "@tradly/platform-core";
// All auth utilities are available
const domain = getDomain();
const authKey = getAuthKey();Complete Example
import {
initializeAuth,
getCurrencies,
getCountries,
getConfigs,
getTranslations,
getHome,
} from "@tradly/platform-core";
async function setupApp() {
// Initialize
initializeAuth("beauty.tradly.co", "production");
// Fetch all data
const [currencies, countries, configs, translations, home] =
await Promise.all([
getCurrencies(),
getCountries(),
getConfigs(),
getTranslations(["common", "validation"]),
getHome(),
]);
console.log("Currencies:", currencies);
console.log("Countries:", countries);
console.log("Configs:", configs);
console.log("Translations:", translations);
if (home.status && home.data) {
console.log("Home feed:", home.data);
}
}
setupApp();Features
- ✅ Automatic Authentication - Automatically uses PK key or auth key from auth package
- ✅ Currency Management - Get all currencies or by ID
- ✅ Country Management - Get all countries, tenant countries, or by ID
- ✅ Configuration Management - Get tenant configs and secure configs
- ✅ Translation Management - Get translations by group names
- ✅ Home Feed Service - Get home page feed data (featured listings, categories, etc.)
- ✅ Built-in Caching - Prevent duplicate API calls with configurable TTL
- ✅ Language Support - Pass language code for localized responses
- ✅ Currency Support - Pass currency code for currency-specific responses
- ✅ TypeScript Support - Full TypeScript definitions
- ✅ Zero Configuration - Works automatically with auth package initialization
- ✅ Multi-Domain Support - Works with auth package's multi-domain configuration
Response Format
All service functions return data in a consistent format:
// Success case
const currencies = await getCurrencies();
// Returns: Currency[] (array of currencies)
// Error case
const currency = await getCurrency(999999);
// Returns: null (if not found or error)For direct API calls using get, post, etc., responses follow this format:
interface ApiResponse<T> {
status: boolean;
data: T;
error?: {
code: number;
message: string;
};
}Error Handling
import { getCurrencies } from "@tradly/platform-core";
try {
const currencies = await getCurrencies();
if (currencies.length === 0) {
console.warn("No currencies found");
}
} catch (error) {
console.error("Error fetching currencies:", error);
}Testing
# Run all tests
npm run test:all
# Run integration tests (against real API)
npm run test:integration
# Run unit tests
npm run test:unit
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverage
# Run tests with UI
npm run test:uiTypeScript
Full TypeScript support with comprehensive type definitions:
import type {
Currency,
Country,
ConfigResponse,
LangifyResponse,
ApiResponse,
RequestOptions,
} from "@tradly/platform-core";
// Home service returns ApiResponse<any>
const homeResponse: ApiResponse<any> = await getHome();
const currencies: Currency[] = await getCurrencies();
const response: ApiResponse<Currency> = await get("/v1/currencies/1");Integration with Auth Package
The utility package automatically integrates with @tradly/auth:
- Initialization: Call
initializeAuth()once (from either package) - Authentication: Utility functions automatically use PK key or auth key
- Configuration: All functions use the same domain and environment
import { initializeAuth } from "@tradly/platform-core";
import { emailLogin } from "@tradly/auth";
// Initialize once
initializeAuth("beauty.tradly.co", "production");
// Login (auth package)
await emailLogin("[email protected]", "password");
// Use utilities (automatically uses auth key from login)
const currencies = await getCurrencies();
const profile = await getUserProfile(); // from auth packageExamples
E-commerce Setup
import {
initializeAuth,
getCurrencies,
getCountries,
getConfigs,
} from "@tradly/platform-core";
async function setupEcommerce() {
initializeAuth("beauty.tradly.co", "production");
// Get available currencies
const currencies = await getCurrencies();
const defaultCurrency = currencies.find((c) => c.default);
// Get available countries
const countries = await getCountries();
// Get store configuration
const configs = await getConfigs();
return {
currencies,
defaultCurrency,
countries,
configs,
};
}Multi-Language Support
import { getTranslations } from "@tradly/platform-core";
async function loadTranslations(language: string) {
const translations = await getTranslations(
["common", "products", "checkout"],
{
language,
}
);
return translations;
}
// Load English translations
const enTranslations = await loadTranslations("en");
// Load Arabic translations
const arTranslations = await loadTranslations("ar");License
ISC
Repository
https://github.com/TRADLY-PLATFORM
