npm package: @kraveir0/webapi-proxy-interceptor
Description: Drop-in replacement for PCF WebAPI that automatically routes calls to your local development proxy.
Author: kraveir0 - filipe@krav.dev
Latest version: 2.0.9

# PCF WebAPI Proxy Interceptor

A TypeScript library that provides a **drop-in replacement** for PCF WebAPI calls, automatically routing them to your local proxy.

## Installation

```bash
npm install @kraveir0/webapi-proxy-interceptor
```

## Quick Start

### Simple Usage (Recommended)

```typescript
import { getWebAPI } from "@kraveir0/webapi-proxy-interceptor";

export class MyControl implements ComponentFramework.StandardControl<{}, {}> {
  private webAPI: any;

  public init(context: ComponentFramework.Context<{}>, ...): void {
    // Automatically uses proxy in local dev, original WebAPI in live environment
    this.webAPI = getWebAPI(context, {
      proxyUrl: "http://localhost:3000"
    });
  }

  private async loadData(): Promise<void> {
    // Use exactly like context.webAPI
    const accounts = await this.webAPI.retrieveMultipleRecords(
      "accounts",
      "$select=name,accountnumber&$top=10"
    );

    const account = await this.webAPI.retrieveRecord(
      "accounts",
      "guid-here",
      { select: ["name", "websiteurl"] }
    );
  }

  public destroy(): void {
    // No cleanup needed!
  }
}
```

### Manual Control

```typescript
import { ProxiedWebAPI } from "@kraveir0/webapi-proxy-interceptor";

export class MyControl implements ComponentFramework.StandardControl<{}, {}> {
  private webAPI: any;

  public init(context: ComponentFramework.Context<{}>, ...): void {
    const isLocalDev = window.location.port === "8181"; // PCF test harness

    if (isLocalDev) {
      // Use proxied implementation for local development
      this.webAPI = new ProxiedWebAPI({
        proxyUrl: "http://localhost:3000",
        debug: true
      });
    } else {
      // Use original WebAPI in production
      this.webAPI = context.webAPI;
    }
  }

  // ... rest of your code
}
```

## Configuration Options

```typescript
const webAPI = getWebAPI(context, {
  proxyUrl: "http://localhost:3000",     // Your local development proxy
  debug: true,                          // Enable detailed logging
  enableInProduction: false,            // Safety: never proxy in production
  timeout: 10000,                       // Request timeout (10 seconds)
  customHeaders: {                      // Add custom headers to requests
    "X-Environment": "development",
    "Authorization": "Bearer token"
  }
});
```

## Environment Detection

The library automatically detects your environment:

- **Local Development** (uses ProxiedWebAPI):
  - PCF Test Harness (port 8181)
  - Localhost development
  - URLs containing "pcf", "harness", etc.

- **Production** (uses original context.webAPI):
  - Deployed PCF components
  - Any non-development environment

## API Reference

### `getWebAPI(context?, config?)`
**Recommended**: Smart factory that returns the appropriate WebAPI implementation.

```typescript
const webAPI = getWebAPI(context, { proxyUrl: "http://localhost:3000" });
```

### `ProxiedWebAPI`
Drop-in replacement for PCF WebAPI with identical interface:

```typescript
const webAPI = new ProxiedWebAPI({ proxyUrl: "http://localhost:3000" });

// All standard PCF WebAPI methods available:
await webAPI.createRecord(entityName, data);
await webAPI.updateRecord(entityName, id, data);
await webAPI.deleteRecord(entityName, id);
await webAPI.retrieveRecord(entityName, id, options);
await webAPI.retrieveMultipleRecords(entityName, query, maxPageSize);
```

### `createWebAPI(context?, config?)`
Alternative factory function with explicit environment detection.


## Local Development Setup

1. **Start your proxy server** (e.g., on `http://localhost:3000`)
2. **Configure the library** to point to your proxy
3. **Develop normally** - WebAPI calls automatically route to your local environment

### Example Proxy Server Setup

Your proxy should handle standard Dataverse Web API endpoints:

```
GET    /api/data/v9.2/accounts?$select=name&$top=5
POST   /api/data/v9.2/accounts
PATCH  /api/data/v9.2/accounts(guid)
DELETE /api/data/v9.2/accounts(guid)
```

## Troubleshooting

### "Proxy request failed" errors
- Ensure your proxy server is running on the configured URL
- Check CORS configuration on your proxy

### Environment detection issues
- Enable debug logging: `debug: true`
- Check console output for environment detection results
- Manually override environment detection if needed

## Related

- [Power Platform CLI](https://docs.microsoft.com/en-us/powerapps/developer/component-framework/get-powerapps-cli)
- [PCF Controls](https://docs.microsoft.com/en-us/powerapps/developer/component-framework/)
- [Dataverse Web API](https://docs.microsoft.com/en-us/powerapps/developer/data-platform/webapi/overview)