npm package: @rolly_ecommerce/rolly-api-client
Description: A flexible, framework-agnostic API client utility for web applications with AI-readable documentation. Perfect for Next.js, React, and any JavaScript framework.
Author: Martinus
Latest version: 1.0.9

# Rolly API Client 🛍️

[![npm version](https://badge.fury.io/js/@your-github-username%2Frolly-api-client.svg)](https://badge.fury.io/js/@your-github-username%2Frolly-api-client)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)
[![Node.js](https://img.shields.io/badge/Node.js-18.0+-green.svg)](https://nodejs.org/)

A flexible, framework-agnostic API client utility for web applications with AI-readable documentation. Perfect for Next.js, React, and any JavaScript framework.

## ✨ Features

- 🚀 **Framework-agnostic** - Works with any JavaScript framework
- 📦 **TypeScript-first** - Full TypeScript support with excellent DX
- 🛍️ **E-commerce ready** - Built-in support for products, carts, shipping, and payments
- 🔧 **Easy to use** - Simple API with sensible defaults
- 📚 **AI-readable** - Comprehensive documentation for AI assistants
- 🎯 **Production-ready** - Battle-tested in real-world applications

## 🚀 Quick Start

### Installation

Choose your preferred package manager:

```bash
# NPM
npm install @your-github-username/rolly-api-client

# Yarn
yarn add @your-github-username/rolly-api-client

# PNPM
pnpm add @your-github-username/rolly-api-client

# Bun
bun add @your-github-username/rolly-api-client
```

### Basic Usage

```typescript
import { RollyClient, ProductService, DEFAULT_CONFIG } from '@your-github-username/rolly-api-client';

// Initialize the client
const client = new RollyClient(DEFAULT_CONFIG);
const productService = new ProductService(client);

// Set your business ID
productService.setBusinessId('your-business-id');

// Get product details
const productDetails = await productService.getProductDetailsByPath('product-slug');
console.log('Product:', productDetails.data.products[0]);

// Create a cart
const cartResponse = await productService.guestAnonymousCart({
  p_cart_information: [{
    product_id: 'product-id',
    quantity: 2
  }]
});

console.log('Order Number:', cartResponse.data.result.order_number);
```

## 📚 API Reference

### RollyClient

Main client class for making API requests.

```typescript
import { RollyClient, DEFAULT_CONFIG } from '@your-github-username/rolly-api-client';

const client = new RollyClient(DEFAULT_CONFIG);
```

#### Methods

- `request(method, url, data?, options?)` - Make HTTP requests
- `get(url, options?)` - Make GET requests
- `post(url, data?, options?)` - Make POST requests
- `put(url, data?, options?)` - Make PUT requests
- `delete(url, options?)` - Make DELETE requests

### ProductService

Service for product-related operations.

```typescript
import { ProductService } from '@your-github-username/rolly-api-client';

const productService = new ProductService(client);
productService.setBusinessId('your-business-id');
```

#### Methods

| Method | Description | Parameters |
|--------|-------------|------------|
| `getProductDetailsByPath(path)` | Get product details by path/slug | `path: string` |
| `getShippingMethods()` | Get available shipping methods | None |
| `getPaymentMethods(orderId)` | Get payment methods for order | `orderId: string` |
| `guestAnonymousCart(cartData)` | Create guest cart | `cartData: CartData` |
| `getEcomOrder(orderId)` | Get order details | `orderId: string` |
| `applyDiscount(code, orderId)` | Apply discount code | `code: string, orderId: string` |
| `editShippingOrder(shippingData)` | Update shipping info | `shippingData: ShippingData` |

### BusinessService

Service for business-related operations.

```typescript
import { BusinessService } from '@your-github-username/rolly-api-client';

const businessService = new BusinessService(client);
```

#### Methods

| Method | Description | Parameters |
|--------|-------------|------------|
| `getBusinessDetails(businessId)` | Get business information | `businessId: string` |

## 💡 Examples

### Complete E-commerce Flow

```typescript
import { RollyClient, ProductService, DEFAULT_CONFIG } from '@your-github-username/rolly-api-client';

async function completeEcommerceFlow() {
  // Initialize client and service
  const client = new RollyClient(DEFAULT_CONFIG);
  const productService = new ProductService(client);
  productService.setBusinessId('your-business-id');

  // 1. Get product details
  const productDetails = await productService.getProductDetailsByPath('product-slug');
  const product = productDetails.data.products[0];

  // 2. Get shipping methods
  const shippingMethods = await productService.getShippingMethods();
  const selectedShipping = shippingMethods.data.result.data[0];

  // 3. Create cart
  const cartResponse = await productService.guestAnonymousCart({
    p_cart_information: [{
      product_id: product.id,
      quantity: 2
    }]
  });

  const order = cartResponse.data.result;

  // 4. Get payment methods
  const paymentMethods = await productService.getPaymentMethods(order.id);

  // 5. Apply discount (optional)
  try {
    const discountResponse = await productService.applyDiscount('DISCOUNT10', order.id);
    console.log('Discount applied:', discountResponse.data.result);
  } catch (error) {
    console.log('No valid discount code');
  }

  console.log('Order completed:', order.order_number);
}
```

### Next.js API Route

```typescript
// app/api/products/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { RollyClient, ProductService, DEFAULT_CONFIG } from '@your-github-username/rolly-api-client';

export async function GET(request: NextRequest) {
  try {
    const client = new RollyClient(DEFAULT_CONFIG);
    const productService = new ProductService(client);
    productService.setBusinessId('your-business-id');

    const { searchParams } = new URL(request.url);
    const productPath = searchParams.get('path');

    if (!productPath) {
      return NextResponse.json({ error: 'Product path required' }, { status: 400 });
    }

    const productDetails = await productService.getProductDetailsByPath(productPath);
    
    return NextResponse.json(productDetails.data);
  } catch (error) {
    return NextResponse.json({ error: 'Failed to fetch product' }, { status: 500 });
  }
}
```

### React Hook

```typescript
// hooks/useRollyClient.ts
import { useState, useEffect } from 'react';
import { RollyClient, ProductService, DEFAULT_CONFIG } from '@your-github-username/rolly-api-client';

export function useProductDetails(productPath: string) {
  const [product, setProduct] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchProduct() {
      try {
        const client = new RollyClient(DEFAULT_CONFIG);
        const productService = new ProductService(client);
        productService.setBusinessId('your-business-id');

        const productDetails = await productService.getProductDetailsByPath(productPath);
        setProduct(productDetails.data);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    }

    if (productPath) {
      fetchProduct();
    }
  }, [productPath]);

  return { product, loading, error };
}

// Usage in component
function ProductPage({ productPath }) {
  const { product, loading, error } = useProductDetails(productPath);

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h1>{product.products[0].name}</h1>
      <p>{product.products[0].description}</p>
    </div>
  );
}
```

## 🎮 Live Demos

### Interactive Demo

Experience the full e-commerce flow with our interactive demo:

```bash
# Launch Next.js demo
npm run nextjs:demo
```

### Package Demos

Run demos locally to see the API in action:

```bash
# Complete e-commerce flow
npm run demo:complete

# Individual functionality demos
npm run demo:product      # Product operations
npm run demo:shipping     # Shipping methods
npm run demo:payment      # Payment methods
npm run demo:cart         # Cart operations
npm run demo:order        # Order management
npm run demo:discount     # Discount codes
npm run demo:all          # All demos
```

## 🛠️ Development

### Prerequisites

- Node.js 18.0.0 or higher
- npm 8.0.0 or higher
- TypeScript 5.0+ (recommended)

### Setup

```bash
# Clone the repository
git clone https://github.com/your-github-username/rolly-api-client.git
cd rolly-api-client

# Install dependencies
npm install

# Build the package
npm run build

# Run tests
npm test

# Start development mode
npm run dev
```

### Available Scripts

| Script | Description |
|--------|-------------|
| `npm run build` | Build the package for production |
| `npm run dev` | Start development mode with watch |
| `npm test` | Run test suite |
| `npm run test:watch` | Run tests in watch mode |
| `npm run test:coverage` | Run tests with coverage report |
| `npm run lint` | Run ESLint |
| `npm run lint:fix` | Fix ESLint issues |
| `npm run type-check` | Run TypeScript type checking |
| `npm run docs:dev` | Start documentation development server |
| `npm run docs:build` | Build documentation |
| `npm run docs:start` | Start documentation production server |

### Testing

```bash
# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage

# Run specific demo
npm run demo:product
```

## 📦 Publishing

### Prepare for Publishing

```bash
# Build the package
npm run build

# Run tests
npm test

# Check for issues
npm run lint
npm run type-check
```

### Publish to NPM

```bash
# Dry run (test without publishing)
npm run publish:dry-run

# Publish patch version (1.0.0 -> 1.0.1)
npm run publish:patch

# Publish minor version (1.0.0 -> 1.1.0)
npm run publish:minor

# Publish major version (1.0.0 -> 2.0.0)
npm run publish:major
```

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

### Development Workflow

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/amazing-feature`
3. Make your changes
4. Add tests for new functionality
5. Run the test suite: `npm test`
6. Commit your changes: `git commit -m 'Add amazing feature'`
7. Push to the branch: `git push origin feature/amazing-feature`
8. Open a Pull Request

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🆘 Support

- 📖 [Documentation](https://rolly-api-client.vercel.app)
- 🐛 [Bug Reports](https://github.com/your-github-username/rolly-api-client/issues)
- 💬 [Discussions](https://github.com/your-github-username/rolly-api-client/discussions)
- 📧 [Email Support](mailto:your.email@example.com)

## 🙏 Acknowledgments

- Built with ❤️ for the JavaScript community
- Inspired by modern API client patterns
- Powered by TypeScript and Rollup

---

<div align="center">
  <p>Made with <span style="color: #FF7E36;">❤️</span> by the Rolly API Client Team</p>
  <p>
    <a href="https://github.com/your-github-username/rolly-api-client">GitHub</a> •
    <a href="https://www.npmjs.com/package/@your-github-username/rolly-api-client">NPM</a> •
    <a href="https://rolly-api-client.vercel.app">Documentation</a>
  </p>
</div>