deckhearth/pages/api/collections/[identifier].js
Randall Stillwell 50a3156b92 🔗 Implement Collection Slug URLs
🎯 Vanity URLs for Collections:
- Added slug-based URLs like /collection/modern-masters-2021
- Backwards compatible with numeric IDs
- SEO-friendly and memorable URLs

🛠️ Slug System:
- Created lib/slug-utils.js with slug generation and validation
- generateSlug() converts names to URL-friendly format
- generateUniqueSlug() handles duplicates with numeric suffixes
- isValidSlug() validates format (lowercase, hyphens, no special chars)

📊 Database Schema:
- Added slug column to collections table with unique constraint
- Migration script adds slugs to existing collections
- Database constraints ensure slug format and uniqueness
- Performance index on slug column

🔌 API Updates:
- Updated collections API to generate slugs for new collections
- New [identifier].js endpoint handles both slugs and IDs
- Thumbnails API supports both slug and ID lookups
- Smart identifier detection (slug vs numeric ID)

🎨 Frontend Integration:
- Collections page uses slugs for navigation
- Fallback to ID if slug not available (backwards compatibility)
- Updated all collection links to use slugs
- Sample collections created with proper slugs

 URL Examples:
- /collection/modern-masters-2021 (new slug format)
- /collection/123 (old ID format still works)
- Automatic redirect potential for future

The collection URLs are now beautiful and shareable! 🚀
2025-07-26 22:06:52 -05:00

217 lines
No EOL
7.4 KiB
JavaScript

import { sql } from '@vercel/postgres';
import { getUserFromRequest } from '../../../lib/permission-middleware';
import { isValidSlug } from '../../../lib/slug-utils';
export default async function handler(req, res) {
// Set CORS headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// Handle preflight requests
if (req.method === 'OPTIONS') {
res.status(200).end();
return;
}
try {
// Get authenticated user
const user = await getUserFromRequest(req);
if (!user) {
return res.status(401).json({ error: 'Authentication required' });
}
const { identifier } = req.query;
if (!identifier) {
return res.status(400).json({ error: 'Collection identifier is required' });
}
// Determine if identifier is a slug or numeric ID
const isSlug = isValidSlug(identifier) || isNaN(parseInt(identifier));
// Build the query based on identifier type
let collectionQuery;
if (isSlug) {
collectionQuery = sql`
SELECT DISTINCT
c.*,
u.email as creator_email,
COUNT(cc.card_id) as card_count,
COALESCE(SUM(cards.market_price * cc.quantity), 0) as total_value,
cp.role as user_role,
CASE
WHEN c.user_id = ${user.userId} THEN 'owner'
WHEN cp.role IS NOT NULL THEN cp.role
ELSE NULL
END as effective_role
FROM collections c
LEFT JOIN users u ON c.user_id = u.id
LEFT JOIN collection_cards cc ON c.id = cc.collection_id
LEFT JOIN cards ON cc.card_id = cards.id
LEFT JOIN collection_permissions cp ON c.id = cp.collection_id AND cp.user_id = ${user.userId} AND cp.status = 'active'
WHERE c.slug = ${identifier}
AND (
c.user_id = ${user.userId} OR
cp.id IS NOT NULL OR
c.is_public = true
)
GROUP BY c.id, u.email, cp.role
`;
} else {
// Numeric ID lookup
const numericId = parseInt(identifier);
collectionQuery = sql`
SELECT DISTINCT
c.*,
u.email as creator_email,
COUNT(cc.card_id) as card_count,
COALESCE(SUM(cards.market_price * cc.quantity), 0) as total_value,
cp.role as user_role,
CASE
WHEN c.user_id = ${user.userId} THEN 'owner'
WHEN cp.role IS NOT NULL THEN cp.role
ELSE NULL
END as effective_role
FROM collections c
LEFT JOIN users u ON c.user_id = u.id
LEFT JOIN collection_cards cc ON c.id = cc.collection_id
LEFT JOIN cards ON cc.card_id = cards.id
LEFT JOIN collection_permissions cp ON c.id = cp.collection_id AND cp.user_id = ${user.userId} AND cp.status = 'active'
WHERE c.id = ${numericId}
AND (
c.user_id = ${user.userId} OR
cp.id IS NOT NULL OR
c.is_public = true
)
GROUP BY c.id, u.email, cp.role
`;
}
const result = await collectionQuery;
if (result.rows.length === 0) {
return res.status(404).json({ error: 'Collection not found or access denied' });
}
const collection = result.rows[0];
if (req.method === 'GET') {
const formattedCollection = {
id: collection.id,
slug: collection.slug,
name: collection.name,
description: collection.description,
tcg: collection.tcg || 'MTG',
cardCount: parseInt(collection.card_count) || 0,
value: parseFloat(collection.total_value) || 0,
lastViewed: collection.updated_at,
createdAt: collection.created_at,
isPublic: collection.is_public || false,
image: collection.image,
tags: collection.tags ? collection.tags.split(',') : [],
creator: collection.creator_email,
userRole: collection.effective_role
};
res.status(200).json(formattedCollection);
} else if (req.method === 'PUT') {
// Only allow updates by owner
if (collection.user_id !== user.userId) {
return res.status(403).json({ error: 'Only collection owners can edit collections' });
}
const { name, description, isPublic, image, tags } = req.body;
// If name is being changed, generate new slug
let updateFields = [];
let updateValues = [];
let paramIndex = 1;
if (name !== undefined && name !== collection.name) {
// Generate new unique slug if name changed
const existingSlugsResult = await sql`SELECT slug FROM collections WHERE slug IS NOT NULL AND id != ${collection.id}`;
const existingSlugs = existingSlugsResult.rows.map(row => row.slug);
const { generateUniqueSlug } = await import('../../../lib/slug-utils');
const newSlug = await generateUniqueSlug(name, existingSlugs);
updateFields.push(`name = $${paramIndex}`, `slug = $${paramIndex + 1}`);
updateValues.push(name, newSlug);
paramIndex += 2;
}
if (description !== undefined) {
updateFields.push(`description = $${paramIndex}`);
updateValues.push(description);
paramIndex++;
}
if (isPublic !== undefined) {
updateFields.push(`is_public = $${paramIndex}`);
updateValues.push(isPublic);
paramIndex++;
}
if (image !== undefined) {
updateFields.push(`image = $${paramIndex}`);
updateValues.push(image);
paramIndex++;
}
if (tags !== undefined) {
updateFields.push(`tags = $${paramIndex}`);
updateValues.push(Array.isArray(tags) ? tags.join(',') : tags);
paramIndex++;
}
if (updateFields.length === 0) {
return res.status(400).json({ error: 'No fields to update' });
}
updateFields.push('updated_at = CURRENT_TIMESTAMP');
updateValues.push(collection.id);
const updateQuery = `
UPDATE collections
SET ${updateFields.join(', ')}
WHERE id = $${paramIndex}
RETURNING *
`;
const updateResult = await sql.query(updateQuery, updateValues);
const updatedCollection = {
id: updateResult.rows[0].id,
slug: updateResult.rows[0].slug,
name: updateResult.rows[0].name,
description: updateResult.rows[0].description,
isPublic: updateResult.rows[0].is_public,
image: updateResult.rows[0].image,
tags: updateResult.rows[0].tags ? updateResult.rows[0].tags.split(',') : []
};
res.status(200).json(updatedCollection);
} else if (req.method === 'DELETE') {
// Only allow deletion by owner
if (collection.user_id !== user.userId) {
return res.status(403).json({ error: 'Only collection owners can delete collections' });
}
// Delete collection and all related data
await sql`DELETE FROM collection_cards WHERE collection_id = ${collection.id}`;
await sql`DELETE FROM collection_permissions WHERE collection_id = ${collection.id}`;
await sql`DELETE FROM collections WHERE id = ${collection.id}`;
res.status(200).json({ message: 'Collection deleted successfully' });
} else {
res.status(405).json({ error: 'Method not allowed' });
}
} catch (error) {
console.error('Collection API error:', error);
res.status(500).json({ error: 'Internal server error' });
}
}