npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@tanqory/api-client

v0.1.5

Published

A TypeScript client library for the Tanqory API.

Readme

@tanqory/api-client

npm version License: MIT Node.js Version

A powerful TypeScript API client for interacting with the Tanqory platform. This library provides a clean and intuitive interface for managing your site's data, including products, collections, pages, and more, with built-in features like automatic token refreshing, flexible query parameters, and full TypeScript support.

Table of Contents

Features

  • 🏗️ Modular Design: Use dedicated classes for each resource (Product, Collection, Page, Post, Menu, etc.)
  • 🔄 RESTful Interface: Methods like all(), find(), and searchByName() provide a familiar experience
  • 🔐 Automatic Token Refresh: The client automatically handles refreshing expired access tokens using a provided refresh token
  • 🔍 Flexible Queries: Easily filter, sort, and paginate data with powerful query options
  • 🌐 Country-specific Content: Support for country-specific product and collection data
  • Lightweight: Minimal dependencies with a clean, simple API
  • 📝 Full TypeScript Support: Built with TypeScript for excellent developer experience and type safety
  • 🛡️ Type Safety: Complete type definitions for all API responses and request parameters

Installation

You can install the library using npm, yarn, or pnpm:

# npm
npm install @tanqory/api-client

# yarn
yarn add @tanqory/api-client

# pnpm
pnpm add @tanqory/api-client

Requirements

  • Node.js 14.0.0 or higher
  • A valid Tanqory site ID, access token, and refresh token

Quick Start

Initialization

First, initialize the client with your credentials. The siteId is essential for all API requests.

const Tanqory = require('@tanqory/api-client');

// Initialize the client
const client = Tanqory.init({
  siteId: "your-site-id",
  accessToken: "your-access-token",
  refreshToken: "your-refresh-token"
});

ES6 Modules & TypeScript

import Tanqory, { TanqoryInitOptions, Product, Collection } from '@tanqory/api-client';

const client = Tanqory.init({
  siteId: "your-site-id",
  accessToken: "your-access-token", 
  refreshToken: "your-refresh-token"
});

// TypeScript provides full intellisense and type checking
const products: Product[] = await client.product.searchByName("T-shirt");

🔒 Security Note: The client automatically refreshes expired access tokens using the refresh token, ensuring uninterrupted API access.

Basic Usage Example

async function example() {
  try {
    // Get all products with TypeScript support
    const products = await client.product.all();
    console.log(`Found ${products?.data?.length || 0} products`);

    // Search for a specific product with type safety
    const searchResults = await client.product.searchByName("T-shirt");
    console.log(`Found ${searchResults.length} matching products`);

    // Get a specific collection with proper typing
    const collection = await client.collection.find("summer-2024");
    console.log(`Collection: ${collection?.name}`);
  } catch (error) {
    console.error('API Error:', error.message);
  }
}

example();

TypeScript Support

This library is built with TypeScript and provides excellent type safety and developer experience.

Type Definitions

All API responses, request parameters, and configuration options are fully typed:

import { 
  TanqoryInitOptions, 
  QueryOptions, 
  Product, 
  Collection, 
  ApiResponse 
} from '@tanqory/api-client';

// Type-safe initialization
const options: TanqoryInitOptions = {
  siteId: "your-site-id",
  accessToken: "your-access-token",
  refreshToken: "your-refresh-token"
};

// Type-safe query options
const queryOptions: QueryOptions = {
  limit: 20,
  sort: 'name',
  order: 'asc',
  search: 'shirt',
  country: 'US'
};

// Type-safe API responses
const response: ApiResponse<Product> = await client.product.all(queryOptions);
const products: Product[] = response.data || [];

Generic Methods

Most methods support generic type parameters for even better type safety:

// Explicit type specification
const products = await client.product.all<Product>({ limit: 10 });
const pages = await client.page.getAllPages<Page>({ search: "about" });

// TypeScript automatically infers return types
const product = await client.product.find("product-123"); // Type: Product | null
const collection = await client.collection.find("collection-456"); // Type: Collection | null

Interface Definitions

Key interfaces you can use in your TypeScript projects:

interface Product extends BaseResource {
  description?: string;
  price?: number;
  currency?: string;
  images?: string[];
  category?: string;
  tags?: string[];
  stock?: number;
  sku?: string;
}

interface Collection extends BaseResource {
  description?: string;
  products?: Product[];
  image?: string;
}

interface QueryOptions {
  limit?: number;
  next?: string;
  sort?: string;
  order?: 'asc' | 'desc';
  search?: string;
  country?: string;
  page?: number;
}

Resources

The client object contains various resource classes that provide methods for interacting with the Tanqory API.

Products

The product resource allows you to manage your site's products with full query capabilities.

// Get all products with default options
const allProducts = await client.product.all();
console.log(allProducts.data);

// Get products with advanced filtering
const filteredProducts = await client.product.all({
  limit: 20,
  sort: 'name',
  order: 'asc',
  search: 'shirt',
  country: 'US'
});

// Find a specific product by ID
const product = await client.product.find("product-id-123");
console.log(product);

// Search for products by name
const foundProducts = await client.product.searchByName("Tanqory Mug");
console.log(`Found ${foundProducts.length} products`);

// Pagination example
let nextToken = '';
do {
  const page = await client.product.all({ 
    limit: 10, 
    next: nextToken 
  });
  
  console.log(`Processing ${page.data.length} products`);
  nextToken = page.next || '';
} while (nextToken);

Pages

The page resource manages pages on your online store. It uses a specific form ID for fetching documents.

// Get all pages with pagination
const pages = await client.page.all({ 
  limit: 10, 
  next: "" 
});
console.log(`Found ${pages.items.length} pages`);

// Get pages with search
const searchedPages = await client.page.all({
  search: "about",
  limit: 5
});

// Find a specific page by ID
const page = await client.page.find("page-id-456");
console.log(page.items[0]);

// Get pages sorted by creation date
const recentPages = await client.page.all({
  sort: 'created_at',
  order: 'desc',
  limit: 20
});

Collections

The collection resource provides methods for managing product collections with the same query capabilities as products.

// Get all collections
const allCollections = await client.collection.all();
console.log(allCollections.items);

// Get collections with filtering and sorting
const sortedCollections = await client.collection.all({
  limit: 15,
  sort: 'created_at',
  order: 'desc',
  country: 'TH'
});

// Find a specific collection by ID
const collection = await client.collection.find("collection-id-789");
console.log(`Collection: ${collection.name}`);

// Search collections by name
const matchingCollections = await client.collection.searchByName("Summer");
console.log(`Found ${matchingCollections.length} summer collections`);

Blog Posts (Post resource)

The post resource is designed for managing blog posts with full query and pagination support.

// Get the latest blog posts
const latestPosts = await client.post.all({ 
  limit: 5,
  sort: 'published_at',
  order: 'desc' 
});
console.log(`Latest ${latestPosts.items.length} posts`);

// Search for posts by keyword
const searchPosts = await client.post.all({
  search: "tutorial",
  limit: 10
});

// Find a specific blog post
const post = await client.post.find("post-id-123");
console.log(`Post: ${post.title}`);

Menus (Menu resource)

You can manage your site's navigation menus with the menu resource.

// Get all menus
const allMenus = await client.menu.all();
console.log(`Found ${allMenus.items.length} menus`);

// Get a specific menu by ID
const mainMenu = await client.menu.find("main-menu-id");
console.log(`Menu: ${mainMenu.name}`);

// Get menus with sorting
const sortedMenus = await client.menu.all({
  sort: 'name',
  order: 'asc'
});

Site Settings

The client provides dedicated resources for accessing site-wide settings and configuration.

General Settings (General resource)

Access your site's general configuration and settings.

// Get general site settings
const generalSettings = await client.general.all();
console.log('Site name:', generalSettings.site_name);
console.log('Currency:', generalSettings.currency);
console.log('Timezone:', generalSettings.timezone);

Policy and Privacy Data (Policy resource)

Retrieve your site's privacy policy and terms of service.

// Get policy and privacy data
const policyData = await client.policy.all();
console.log('Privacy policy:', policyData.privacy_policy);
console.log('Terms of service:', policyData.terms_of_service);

Error Handling

The client provides comprehensive error handling with specific error types:

try {
  const product = await client.product.find("non-existent-id");
} catch (error) {
  if (error.status === 404) {
    console.log('Product not found');
  } else if (error.status === 401) {
    console.log('Authentication failed - check your tokens');
  } else if (error.status === 429) {
    console.log('Rate limit exceeded - please retry later');
  } else {
    console.error('API Error:', error.message);
  }
}

Token Refresh Handling

The client automatically handles token refresh, but you can also handle refresh failures:

client.on('tokenRefreshFailed', (error) => {
  console.error('Failed to refresh token:', error);
  // Handle re-authentication flow
});

client.on('tokenRefreshed', (newTokens) => {
  console.log('Tokens refreshed successfully');
  // Optionally store new tokens
});

API Reference

Common Query Options

Most resource methods accept an options object with the following parameters:

| Parameter | Type | Description | Default | |-----------|------|-------------|---------| | limit | number | Number of items to return | 50 | | next | string | Pagination token for next page | "" | | sort | string | Field to sort by | "created_at" | | order | string | Sort order: "asc" or "desc" | "desc" | | search | string | Search term to filter results | "" | | country | string | Country code for localized content | "" |

client.product

Manage products and product data.

Methods

  • all(options?): Fetches all products with optional filtering, sorting, and pagination

    const products = await client.product.all({
      limit: 20,
      sort: 'name',
      order: 'asc',
      search: 'shirt',
      country: 'US'
    });
  • find(id): Fetches a single product by its ID

    const product = await client.product.find("product-123");
  • searchByName(name): Searches products by name

    const results = await client.product.searchByName("T-shirt");

client.collection

Manage product collections.

Methods

  • all(options?): Fetches all collections (supports same options as products)
  • find(id): Fetches a single collection by its ID
  • searchByName(name): Searches collections by name

client.page

Manage site pages and content.

Methods

  • all(options?): Fetches all pages (supports limit, next, sort, order, search)
  • find(id): Fetches a single page by its ID

client.post

Manage blog posts and articles.

Methods

  • all(options?): Fetches all blog posts (supports limit, next, sort, order, search)
  • find(id): Fetches a single blog post by its ID

client.menu

Manage navigation menus.

Methods

  • all(options?): Fetches all menus (supports limit, next, sort, order, search)
  • find(id): Fetches a single menu by its ID

client.general

Access general site settings.

Methods

  • all(): Fetches the site's general settings and configuration

client.policy

Access privacy and policy data.

Methods

  • all(): Fetches the site's privacy policy and terms of service

Response Format

All API responses follow a consistent format:

// For list operations (all, search)
{
  "data": [...],      // Array of items
  "items": [...],     // Alternative array format (some endpoints)
  "next": "token",    // Pagination token
  "total": 100,       // Total count (when available)
  "limit": 20         // Applied limit
}

// For single item operations (find)
{
  "id": "item-123",
  "name": "Item Name",
  // ... other item properties
}

Contributing

We welcome contributions to the Tanqory API client! Here's how you can help:

Getting Started

  1. Fork the repository on GitHub
  2. Clone your fork locally
    git clone https://github.com/your-username/api-client.git
    cd api-client
  3. Install dependencies
    npm install

Development Workflow

  1. Create a feature branch
    git checkout -b feature/your-feature-name
  2. Make your changes and test them thoroughly
  3. Commit your changes with a descriptive message
    git commit -m "Add feature: your feature description"
  4. Push to your fork
    git push origin feature/your-feature-name
  5. Create a Pull Request on GitHub

Guidelines

  • Follow the existing code style and conventions
  • Write clear, descriptive commit messages
  • Add tests for new features when possible
  • Update documentation for any API changes
  • Ensure all existing tests pass

Reporting Issues

Please use the GitHub issue tracker to report bugs or request features. When reporting bugs, please include:

  • A clear description of the issue
  • Steps to reproduce the problem
  • Expected vs actual behavior
  • Your environment details (Node.js version, OS, etc.)

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support


Made with ❤️ by TANQ PTE. LTD.