Skip to content

📚 Create API Documentation #71

Description

@desoga10

Description

Document all Supabase queries, database schema, RLS policies, and API patterns to help new developers understand and contribute to the project.

Why This Matters

  • Onboard new contributors faster
  • Reduce repetitive questions
  • Establish clear data access patterns
  • Document security policies
  • Serve as reference for existing developers

Documentation Scope

1. Database Schema Documentation

  • ER Diagram - Visual representation of tables and relationships
  • Table Descriptions - Purpose of each table
  • Column Details - Data types, constraints, defaults
  • Relationships - Foreign keys and references
  • Indexes - Performance optimization details

2. Row Level Security (RLS) Policies

  • List all RLS policies per table
  • Explain what each policy does
  • Show SQL for each policy
  • Document security implications

3. Common Queries

  • Frequently used Supabase queries
  • Code examples for each operation (CRUD)
  • Search and filter patterns
  • Aggregation queries (totals, counts, etc.)
  • Join queries with related tables

4. Data Models/Types

  • TypeScript interfaces for all tables
  • Request/response types
  • DTO (Data Transfer Object) definitions

5. Service Documentation

  • Document all service methods
  • Parameters and return types
  • Error handling patterns
  • Usage examples

6. Setup Guide for Developers

  • Step-by-step setup instructions
  • Environment configuration
  • Database setup process
  • Running SQL schema files
  • Troubleshooting common issues

Documentation Structure

Organize docs in the repository:

docs/
├── README.md                 # Overview and quick links
├── database/
│   ├── schema.md            # Complete schema documentation
│   ├── erd.png              # Entity Relationship Diagram
│   ├── rls-policies.md      # All RLS policies
│   └── common-queries.md    # Query examples
├── api/
│   ├── services.md          # Service documentation
│   ├── models.md            # TypeScript interfaces
│   └── error-handling.md    # Error patterns
├── guides/
│   ├── setup.md             # Developer setup
│   ├── contributing.md      # How to contribute
│   └── deployment.md        # Deployment guide
└── examples/
    ├── create-invoice.md    # Example workflows
    └── search-filter.md     # Search examples

Schema Documentation Example

Template for each table:

### `invoices` Table

**Purpose:** Stores all invoice records created by users.

**Columns:**
| Column | Type | Constraints | Description |
|--------|------|-------------|-------------|
| id | UUID | PRIMARY KEY | Unique invoice identifier |
| user_id | UUID | REFERENCES auth.users, NOT NULL | Invoice owner |
| invoice_number | VARCHAR(50) | UNIQUE, NOT NULL | Invoice number (INV-001) |
| client_name | VARCHAR(255) | NOT NULL | Client name |
| status | VARCHAR(20) | CHECK IN (...) | paid/unpaid/draft/overdue |
| total_amount | DECIMAL(10,2) | NOT NULL, >= 0 | Total invoice amount |
| created_at | TIMESTAMP | DEFAULT NOW() | Creation timestamp |

**Indexes:**
- `idx_invoices_user_id` on user_id
- `idx_invoices_status` on status

**Relationships:**
- One-to-many with `invoice_items`
- Many-to-one with `auth.users`

**RLS Policies:**
- Users can only view/edit their own invoices
- See rls-policies.md for details

RLS Documentation Example

### Invoice RLS Policies

#### SELECT Policy
```sql
CREATE POLICY "Users view own invoices"
ON invoices FOR SELECT
USING (auth.uid() = user_id);
```
**Purpose:** Users can only see their own invoices  
**Impact:** All SELECT queries automatically filtered

#### INSERT Policy
```sql
CREATE POLICY "Users create own invoices"
ON invoices FOR INSERT
WITH CHECK (auth.uid() = user_id);
```
**Purpose:** Prevent creating invoices for other users

Common Queries Documentation

### Get All Invoices for User
```typescript
const { data, error } = await supabase
  .from('invoices')
  .select('*')
  .order('created_at', { ascending: false });
```

### Get Invoice with Items
```typescript
const { data, error } = await supabase
  .from('invoices')
  .select(`
    *,
    invoice_items (*)
  `)
  .eq('id', invoiceId)
  .single();
```

### Search Invoices
```typescript
const { data, error } = await supabase
  .from('invoices')
  .select('*')
  .or(`invoice_number.ilike.%${query}%,client_name.ilike.%${query}%`);
```

Service Documentation Example

### InvoiceService

**Location:** `src/app/services/invoice.service.ts`

#### getInvoices()
**Purpose:** Fetch all invoices for current user  
**Returns:** `Observable<Invoice[]>`  
**Example:**
```typescript
this.invoiceService.getInvoices().subscribe(invoices => {
  console.log(invoices);
});
```

#### createInvoice(invoice)
**Purpose:** Create new invoice  
**Parameters:** `CreateInvoiceDto`  
**Returns:** `Observable<Invoice>`  
**Side Effects:** Auto-generates invoice number

Data Models Documentation

### Invoice Interface
```typescript
interface Invoice {
  id: string;
  user_id: string;
  invoice_number: string;
  client_name: string;
  status: 'draft' | 'paid' | 'unpaid' | 'overdue';
  total_amount: number;
  currency: string;
  issue_date: string;
  created_at: string;
}
```

### CreateInvoiceDto
```typescript
interface CreateInvoiceDto {
  client_name: string;
  status?: 'draft' | 'unpaid';
  currency?: string;
  issue_date: string;
  items: CreateInvoiceItemDto[];
}
```

Setup Guide Template

## Developer Setup

### Prerequisites
- Node.js 18+
- Angular CLI
- Supabase account

### Steps

1. **Clone repository**
2. **Install dependencies:** `npm install`
3. **Create Supabase project**
4. **Configure environment variables**
5. **Run database schema files (in order):**
   - user-schema.sql
   - invoice-schema.sql
   - invoice-items-schema.sql
   - seeder.sql
6. **Start dev server:** `ng serve`

### Troubleshooting
- **Can't connect to Supabase:** Check API keys
- **RLS errors:** Ensure you're authenticated
- **Queries fail:** Verify RLS policies are set

Tools for Documentation

Database Documentation:

  • dbdiagram.io - Create ER diagrams
  • DbDocs - Auto-generate from schema
  • Draw.io - Manual diagrams

Code Documentation:

  • Compodoc - Angular-specific docs generator
  • TypeDoc - Generate from TypeScript comments

Priority Areas (Start Here)

  1. Database Schema ⭐ Most critical
  2. Common Queries ⭐ Helps contributors immediately
  3. Setup Guide ⭐ Reduces onboarding friction
  4. RLS Policies - Important for security
  5. Service Documentation - Useful for features

Acceptance Criteria

  • Database schema fully documented
  • ER diagram created and included
  • All tables and columns described
  • RLS policies documented with examples
  • Common queries documented
  • Service methods documented
  • Data models/interfaces documented
  • Setup guide complete and tested
  • Documentation organized in docs/ folder
  • README updated with links to docs
  • All SQL files have comments

Documentation Standards

SQL Comments:

-- Create invoices table to store invoice records
-- Each invoice belongs to a user and has multiple items
CREATE TABLE invoices (
  id UUID PRIMARY KEY,
  -- User who created this invoice
  user_id UUID REFERENCES auth.users(id)
);

TypeScript Comments:

/**
 * Fetches invoice with all line items
 * @param invoiceId - Invoice UUID
 * @returns Observable with invoice data
 * @throws Error if not found
 */
getInvoiceById(id: string): Observable<Invoice>

Testing Checklist

  • All code examples work
  • Setup guide tested by new developer
  • Schema documentation accurate
  • RLS policies match actual database
  • No broken links in documentation
  • Screenshots/diagrams up to date

Priority

High - Foundational for project growth

Estimated Complexity

Low-Medium - Mostly writing, some tooling

Estimated Time

  • Database docs: 4-6 hours
  • Query examples: 2-3 hours
  • Setup guide: 2-3 hours
  • Service docs: 3-4 hours
  • Total: 11-16 hours

Implementation Phases

Phase 1: Database schema + ER diagram
Phase 2: Common queries + examples
Phase 3: Setup guide
Phase 4: RLS policies
Phase 5: Service documentation

Call for Contributors

Great first contribution! Pick any section and start documenting. Even partial documentation helps. No coding required - just clear writing.

Resources

Notes

Focus on practical examples over theory. Show real code that developers can copy and use. Update docs when features change.

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentationgood first issueGood for newcomershelp wantedExtra attention is needed

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions