@vibeclasses/shared-types
v1.0.8
Published
Shared TypeScript types for article management system
Downloads
11
Maintainers
Readme
@your-org/shared-types
Shared TypeScript types and utilities for the Article Management System. This package provides type-safe contracts across your entire stack - from database to API to frontend.
๐ Quick Start
npm install @your-org/shared-typesimport { Article, CreateArticleRequest, generateSlug } from '@your-org/shared-types'
// Type-safe article creation
const request: CreateArticleRequest = {
url: 'https://example.com/article'
}
// Generate URL-friendly slugs
const slug = generateSlug('My Amazing Article Title') // "my-amazing-article-title"๐ฆ What's Included
Domain Types
Core business entities with full type safety:
import { Article, Tag, User } from '@your-org/shared-types'
const article: Article = {
id: 'uuid',
url: 'https://example.com',
title: 'Sample Article',
slug: 'sample-article',
summary: 'Article description',
image: {
src: 'https://example.com/image.jpg',
alt: 'Article image'
},
publishDate: new Date(),
source: 'example.com',
tags: [{ name: 'tech', slug: 'tech' }],
active: true
}API Contracts
Request/response types for consistent API communication:
import { CreateArticleRequest, ApiResponse, PaginationRequest } from '@your-org/shared-types'
// API request types
const createRequest: CreateArticleRequest = {
url: 'https://example.com/article'
}
// Standardized API responses
const response: ApiResponse<Article[]> = {
data: articles,
meta: {
total: 100,
page: 1,
limit: 10,
totalPages: 10
}
}Database Integration
Seamless conversion between database rows and domain objects:
import { toArticleFromRow, toArticleRow, ArticleRow } from '@your-org/shared-types'
// Convert database row to domain object
const article = toArticleFromRow(dbRow)
// Convert domain object to database row
const dbData = toArticleRow(article)Utility Functions
Helper functions for common operations:
import { generateSlug, validateUrl, formatDate } from '@your-org/shared-types'
const slug = generateSlug('My Article Title!') // "my-article-title"
const isValid = validateUrl('https://example.com') // true
const formatted = formatDate(new Date()) // "January 15, 2025"๐๏ธ Architecture
This package is organized into logical modules:
src/
โโโ domain/ # Core business types (Article, Tag, User)
โโโ api/ # HTTP request/response contracts
โโโ database/ # Database row types and transformations
โโโ utils/ # Utility functions and helpers
โโโ index.ts # Main exportsDomain Layer
Pure TypeScript interfaces representing your business entities:
Article- Core article entity with metadataTag- Article categorization systemUser- User management (admin/editor roles)
API Layer
HTTP communication contracts:
- Request types (
CreateArticleRequest,UpdateArticleRequest) - Response types (
ApiResponse<T>,ArticleListResponse) - Common types (
PaginationMeta,ApiError)
Database Layer
Integration with your database schema:
- Row types (
ArticleRow,TagRow) - Direct database mappings - Transform functions - Convert between database and domain
- Input types - For database operations
Utils Layer
Reusable helper functions:
generateSlug()- URL-friendly slug generationvalidateUrl()- URL validationformatDate()- Date formatting utilities
๐ง Development Setup
Prerequisites
- Node.js 18+
- TypeScript 5.0+
- npm or yarn
Local Development
# Clone and install
git clone <repository-url>
cd shared-types
npm install
# Development workflow
npm run dev # Watch mode for development
npm run build # Compile TypeScript
npm run clean # Clean build artifacts
# Sync with database schema (if using Prisma)
npm run sync-prisma # Sync types from API projectBuilding and Publishing
# Build for production
npm run build
# Run type checking
npm run type-check
# Publish new version
npm run release # Automatically bumps version and publishes๐ Integration Guide
With Next.js Frontend
// pages/articles.tsx
import { Article, ArticleListResponse } from '@your-org/shared-types'
export default function ArticlesPage() {
const [articles, setArticles] = useState<Article[]>([])
useEffect(() => {
fetch('/api/articles')
.then(res => res.json() as Promise<ArticleListResponse>)
.then(data => setArticles(data.articles))
}, [])
// Type-safe rendering...
}With Fastify/Express API
// api/routes/articles.ts
import { CreateArticleRequest, ApiResponse } from '@your-org/shared-types'
app.post<{ Body: CreateArticleRequest }>('/articles', async (request, reply) => {
const { url } = request.body // Fully typed!
const response: ApiResponse<{ jobId: string }> = {
data: { jobId: 'uuid' },
message: 'Article extraction started'
}
reply.send(response)
})With Supabase Database
// lib/articles.ts
import { supabase } from './supabase'
import { toArticleFromRow, ArticleRow } from '@your-org/shared-types'
export async function getArticles() {
const { data } = await supabase
.from('articles')
.select('*')
.returns<ArticleRow[]>()
return data?.map(toArticleFromRow) || []
}๐ Examples
Creating an Article Workflow
import {
CreateArticleRequest,
ArticleExtractionResult,
toArticleRow,
generateSlug
} from '@your-org/shared-types'
// 1. Frontend sends request
const request: CreateArticleRequest = {
url: 'https://techcrunch.com/article'
}
// 2. Background job extracts data
const extracted: ArticleExtractionResult = {
url: request.url,
title: 'Amazing Tech News',
summary: 'This is groundbreaking...',
image: { src: 'image.jpg', alt: 'Tech news' },
source: 'techcrunch.com',
tags: ['tech', 'startup', 'innovation']
}
// 3. Save to database
const slug = generateSlug(extracted.title)
const dbData = toArticleRow({
...extracted,
slug,
publishDate: new Date()
})
await supabase.from('articles').insert(dbData)Real-time Updates
import { Article } from '@your-org/shared-types'
// Subscribe to article updates
useEffect(() => {
const channel = supabase
.channel('article-updates')
.on('broadcast', { event: 'article-created' }, (payload) => {
// payload is fully typed based on your schema
refreshArticles()
})
.subscribe()
return () => supabase.removeChannel(channel)
}, [])๐งช Testing
The package includes type definitions that help catch errors at compile time:
import { Article, validateUrl } from '@your-org/shared-types'
// TypeScript will catch this error
const invalidArticle: Article = {
url: 'invalid-url', // โ
String is valid
title: 123, // โ TypeError: number is not assignable to string
}
// Runtime validation
if (!validateUrl(url)) {
throw new Error('Invalid URL format')
}๐ Deployment
Publishing to npm
# Public registry (free)
npm publish --access public
# Private registry (paid)
npm publishUsing in Monorepo
{
"dependencies": {
"@your-org/shared-types": "workspace:*"
}
}Direct File Reference
{
"dependencies": {
"shared-types": "file:../shared-types"
}
}๐ง Configuration
TypeScript Configuration
Ensure your consuming projects have compatible TypeScript settings:
{
"compilerOptions": {
"strict": true,
"esModuleInterop": true,
"moduleResolution": "node"
}
}Environment Setup
For Prisma integration, set up these environment variables:
# In your API project
DATABASE_URL="postgresql://..."
# In shared-types (for sync script)
API_PROJECT_PATH="../api"๐ API Reference
Core Types
| Type | Description | Usage |
|------|-------------|-------|
| Article | Main article entity | Domain objects, API responses |
| Tag | Article categorization | Tagging system, filtering |
| User | User management | Authentication, authorization |
| ApiResponse<T> | Standardized API response | All API endpoints |
Utility Functions
| Function | Parameters | Returns | Description |
|----------|------------|---------|-------------|
| generateSlug(text) | string | string | Creates URL-friendly slug |
| validateUrl(url) | string | boolean | Validates URL format |
| formatDate(date) | Date, locale? | string | Formats date for display |
Transform Functions
| Function | Purpose | Usage |
|----------|---------|-------|
| toArticleFromRow() | DB row โ Domain object | Reading from database |
| toArticleRow() | Domain object โ DB row | Writing to database |
| toTagFromRow() | DB row โ Tag object | Tag operations |
๐ค Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature/new-type - Make your changes and add tests
- Ensure TypeScript compilation:
npm run build - Submit a pull request
Guidelines
- Follow existing naming conventions
- Add JSDoc comments for public APIs
- Update version in
package.json - Add examples for new features
๐ License
MIT License - see LICENSE file for details.