npm package: @fnd-platform/api
Description: Projen project class for generating Lambda API packages in fnd-platform
Latest version: 1.0.0-alpha.13

# @fnd-platform/api

Projen project class and runtime utilities for building serverless Lambda APIs with type-safe handlers, middleware patterns, and DynamoDB integration.

## Installation

```bash
npm install -D @fnd-platform/api
# or
pnpm add -D @fnd-platform/api
```

## Quick Start

Add an API package to your monorepo in `.projenrc.ts`:

```typescript
import { FndMonorepoProject } from '@fnd-platform/core';
import { FndApiProject } from '@fnd-platform/api';

const monorepo = new FndMonorepoProject({
  name: 'my-app',
  defaultReleaseBranch: 'main',
});

const api = new FndApiProject({
  parent: monorepo,
  name: 'api',
  outdir: 'packages/api',
  dynamodb: true,
  cognito: true,
});

monorepo.synth();
```

## Configuration Options

| Option     | Type                 | Default           | Description                    |
| ---------- | -------------------- | ----------------- | ------------------------------ |
| `parent`   | `FndMonorepoProject` | **required**      | Parent monorepo                |
| `name`     | `string`             | **required**      | Package name                   |
| `outdir`   | `string`             | `packages/{name}` | Output directory               |
| `dynamodb` | `boolean`            | `true`            | Include DynamoDB utilities     |
| `cognito`  | `boolean`            | `true`            | Include Cognito authentication |
| `cors`     | `boolean`            | `true`            | Enable CORS support            |

## Features

- **Lambda Handlers** - Type-safe handler patterns with middleware support
- **Response Helpers** - Consistent JSON responses with proper status codes
- **Error Classes** - Structured error handling with automatic response mapping
- **Middleware Composition** - Composable middleware for auth, validation, CORS, logging
- **Request Utilities** - Parse body, path params, query params, and user context

## Examples

### Basic Handler

```typescript
import { APIGatewayProxyHandler } from 'aws-lambda';
import { success, notFound } from '@fnd-platform/api';

export const handler: APIGatewayProxyHandler = async (event) => {
  const data = { message: 'Hello, World!' };
  return success(data);
};
```

### Handler with Middleware

```typescript
import { compose, withAuth, withErrorHandler, withValidation } from '@fnd-platform/api';
import { z } from 'zod';

const schema = z.object({
  title: z.string().min(1).max(200),
  content: z.string(),
});

export const handler = compose(
  withErrorHandler(),
  withAuth(),
  withValidation(schema)
)(async (event) => {
  const body = JSON.parse(event.body || '{}');
  // body is validated against schema
  return success({ id: '123', ...body }, 201);
});
```

### Using Request Utilities

```typescript
import { requirePathParam, getQueryParam, parseBody, getUserId } from '@fnd-platform/api';

export const handler = withAuth(async (event) => {
  const id = requirePathParam(event, 'id');
  const page = getQueryParam(event, 'page', '1');
  const body = parseBody(event);
  const userId = getUserId(event);

  // ... handler logic
});
```

## API Reference

See the [full API documentation](../../docs/api/modules/api_src.html) for detailed type definitions and examples.

### Project Class

- `FndApiProject` - Projen project class for API packages

### Response Helpers

```typescript
import {
  success, // 200 OK (or custom status)
  created, // 201 Created
  error, // 500 Internal Server Error (or custom)
  notFound, // 404 Not Found
  unauthorized, // 401 Unauthorized
  forbidden, // 403 Forbidden
  badRequest, // 400 Bad Request
} from '@fnd-platform/api';
```

### Error Classes

```typescript
import {
  ApiError, // Base error class
  NotFoundError, // 404 errors
  ValidationError, // 400/422 validation errors
  UnauthorizedError, // 401 errors
  ForbiddenError, // 403 errors
  ConflictError, // 409 conflict errors
} from '@fnd-platform/api';
```

### Middleware

```typescript
import {
  compose, // Compose multiple middleware
  withErrorHandler, // Catch errors and return proper responses
  withAuth, // Validate JWT tokens from Cognito
  withValidation, // Validate request body with Zod
  withCors, // Add CORS headers
  withLogging, // Log requests and responses
} from '@fnd-platform/api';
```

### Request Utilities

```typescript
import {
  parseBody, // Parse JSON body
  requirePathParam, // Get required path parameter
  getQueryParam, // Get query parameter with default
  getUserId, // Get authenticated user ID
} from '@fnd-platform/api';
```

### Types

```typescript
import type {
  FndApiProjectOptions,
  Handler,
  AuthenticatedEvent,
  AuthenticatedHandler,
  CognitoClaims,
  PaginatedRequest,
  PaginatedResponse,
  MiddlewareHandler,
  Middleware,
  ValidatedEvent,
  SuccessResponse,
  ErrorResponse,
  ErrorHandlerOptions,
  AuthOptions,
  CorsOptions,
  LoggingOptions,
} from '@fnd-platform/api';
```

## Requirements

- Node.js 20+
- pnpm 8+
- @fnd-platform/core

## Related

- [@fnd-platform/core](../core/README.md) - Core Projen project classes
- [@fnd-platform/dynamodb](../dynamodb/README.md) - DynamoDB utilities
- [@fnd-platform/cognito-auth](../cognito-auth/README.md) - Cognito authentication
- [@fnd-platform/constructs](../constructs/README.md) - CDK constructs for deployment

## License

MIT