Implement comprehensive error handling
- Add try-catch blocks to all server actions with retry logic - Implement exponential backoff retry mechanism for database operations - Add input validation to all server actions - Create ErrorBoundary component for React error handling - Add page-level error handlers (error.tsx, global-error.tsx) - Add route-specific error pages for list and item routes - Enhance database connection with graceful error handling - Add user-friendly error messages throughout the application - Implement proper error logging for debugging Task: 16. Implement error handling Requirements: All (error handling is cross-cutting)
This commit is contained in:
@@ -199,7 +199,7 @@
|
|||||||
- Implement skeleton loaders
|
- Implement skeleton loaders
|
||||||
- _Requirements: 7.3_
|
- _Requirements: 7.3_
|
||||||
|
|
||||||
- [ ] 16. Implement error handling
|
- [-] 16. Implement error handling
|
||||||
- Add try-catch blocks to all server actions
|
- Add try-catch blocks to all server actions
|
||||||
- Implement error boundaries in React components
|
- Implement error boundaries in React components
|
||||||
- Add user-friendly error messages
|
- Add user-friendly error messages
|
||||||
|
|||||||
46
app/error.tsx
Normal file
46
app/error.tsx
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useEffect } from 'react'
|
||||||
|
import { AlertTriangle } from 'lucide-react'
|
||||||
|
|
||||||
|
export default function Error({
|
||||||
|
error,
|
||||||
|
reset,
|
||||||
|
}: {
|
||||||
|
error: Error & { digest?: string }
|
||||||
|
reset: () => void
|
||||||
|
}) {
|
||||||
|
useEffect(() => {
|
||||||
|
console.error('Page error:', error)
|
||||||
|
}, [error])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center p-4 bg-gray-50">
|
||||||
|
<div className="max-w-md w-full bg-white rounded-lg shadow-lg p-6 sm:p-8">
|
||||||
|
<div className="flex items-center justify-center w-12 h-12 sm:w-16 sm:h-16 bg-red-100 rounded-full mx-auto mb-4">
|
||||||
|
<AlertTriangle className="w-6 h-6 sm:w-8 sm:h-8 text-red-600" />
|
||||||
|
</div>
|
||||||
|
<h2 className="text-xl sm:text-2xl font-bold text-gray-900 text-center mb-2">
|
||||||
|
Something went wrong
|
||||||
|
</h2>
|
||||||
|
<p className="text-sm sm:text-base text-gray-600 text-center mb-6">
|
||||||
|
{error.message || 'We encountered an unexpected error. Please try again.'}
|
||||||
|
</p>
|
||||||
|
<div className="flex flex-col sm:flex-row gap-3">
|
||||||
|
<button
|
||||||
|
onClick={reset}
|
||||||
|
className="flex-1 px-4 py-3 bg-blue-500 hover:bg-blue-600 active:bg-blue-700 text-white rounded-lg transition-colors font-medium text-sm sm:text-base tap-target"
|
||||||
|
>
|
||||||
|
Try Again
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => window.location.href = '/'}
|
||||||
|
className="flex-1 px-4 py-3 bg-gray-200 hover:bg-gray-300 active:bg-gray-400 text-gray-700 rounded-lg transition-colors font-medium text-sm sm:text-base tap-target"
|
||||||
|
>
|
||||||
|
Go Home
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
50
app/global-error.tsx
Normal file
50
app/global-error.tsx
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useEffect } from 'react'
|
||||||
|
import { AlertTriangle } from 'lucide-react'
|
||||||
|
|
||||||
|
export default function GlobalError({
|
||||||
|
error,
|
||||||
|
reset,
|
||||||
|
}: {
|
||||||
|
error: Error & { digest?: string }
|
||||||
|
reset: () => void
|
||||||
|
}) {
|
||||||
|
useEffect(() => {
|
||||||
|
console.error('Global error:', error)
|
||||||
|
}, [error])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<html lang="en">
|
||||||
|
<body className="bg-gray-50 min-h-screen">
|
||||||
|
<div className="min-h-screen flex items-center justify-center p-4">
|
||||||
|
<div className="max-w-md w-full bg-white rounded-lg shadow-lg p-6 sm:p-8">
|
||||||
|
<div className="flex items-center justify-center w-12 h-12 sm:w-16 sm:h-16 bg-red-100 rounded-full mx-auto mb-4">
|
||||||
|
<AlertTriangle className="w-6 h-6 sm:w-8 sm:h-8 text-red-600" />
|
||||||
|
</div>
|
||||||
|
<h2 className="text-xl sm:text-2xl font-bold text-gray-900 text-center mb-2">
|
||||||
|
Application Error
|
||||||
|
</h2>
|
||||||
|
<p className="text-sm sm:text-base text-gray-600 text-center mb-6">
|
||||||
|
A critical error occurred. Please refresh the page or contact support if the problem persists.
|
||||||
|
</p>
|
||||||
|
<div className="flex flex-col sm:flex-row gap-3">
|
||||||
|
<button
|
||||||
|
onClick={reset}
|
||||||
|
className="flex-1 px-4 py-3 bg-blue-500 hover:bg-blue-600 active:bg-blue-700 text-white rounded-lg transition-colors font-medium text-sm sm:text-base"
|
||||||
|
>
|
||||||
|
Try Again
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => window.location.href = '/'}
|
||||||
|
className="flex-1 px-4 py-3 bg-gray-200 hover:bg-gray-300 active:bg-gray-400 text-gray-700 rounded-lg transition-colors font-medium text-sm sm:text-base"
|
||||||
|
>
|
||||||
|
Go Home
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import './globals.css'
|
|||||||
import ServiceWorkerRegistration from '@/components/ServiceWorkerRegistration'
|
import ServiceWorkerRegistration from '@/components/ServiceWorkerRegistration'
|
||||||
import OfflineIndicator from '@/components/OfflineIndicator'
|
import OfflineIndicator from '@/components/OfflineIndicator'
|
||||||
import { ToastProvider } from '@/components/ToastContainer'
|
import { ToastProvider } from '@/components/ToastContainer'
|
||||||
|
import ErrorBoundary from '@/components/ErrorBoundary'
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: 'Ultimate Lists',
|
title: 'Ultimate Lists',
|
||||||
@@ -68,11 +69,13 @@ export default function RootLayout({
|
|||||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||||
</head>
|
</head>
|
||||||
<body className="bg-gray-50 min-h-screen">
|
<body className="bg-gray-50 min-h-screen">
|
||||||
|
<ErrorBoundary>
|
||||||
<ToastProvider>
|
<ToastProvider>
|
||||||
<ServiceWorkerRegistration />
|
<ServiceWorkerRegistration />
|
||||||
<OfflineIndicator />
|
<OfflineIndicator />
|
||||||
{children}
|
{children}
|
||||||
</ToastProvider>
|
</ToastProvider>
|
||||||
|
</ErrorBoundary>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
)
|
)
|
||||||
|
|||||||
53
app/list/[id]/error.tsx
Normal file
53
app/list/[id]/error.tsx
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useEffect } from 'react'
|
||||||
|
import { AlertTriangle } from 'lucide-react'
|
||||||
|
import Link from 'next/link'
|
||||||
|
|
||||||
|
export default function ListError({
|
||||||
|
error,
|
||||||
|
reset,
|
||||||
|
}: {
|
||||||
|
error: Error & { digest?: string }
|
||||||
|
reset: () => void
|
||||||
|
}) {
|
||||||
|
useEffect(() => {
|
||||||
|
console.error('List page error:', error)
|
||||||
|
}, [error])
|
||||||
|
|
||||||
|
const isNotFound = error.message.includes('not found')
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center p-4 bg-gray-50">
|
||||||
|
<div className="max-w-md w-full bg-white rounded-lg shadow-lg p-6 sm:p-8">
|
||||||
|
<div className="flex items-center justify-center w-12 h-12 sm:w-16 sm:h-16 bg-red-100 rounded-full mx-auto mb-4">
|
||||||
|
<AlertTriangle className="w-6 h-6 sm:w-8 sm:h-8 text-red-600" />
|
||||||
|
</div>
|
||||||
|
<h2 className="text-xl sm:text-2xl font-bold text-gray-900 text-center mb-2">
|
||||||
|
{isNotFound ? 'List Not Found' : 'Error Loading List'}
|
||||||
|
</h2>
|
||||||
|
<p className="text-sm sm:text-base text-gray-600 text-center mb-6">
|
||||||
|
{isNotFound
|
||||||
|
? 'The list you are looking for does not exist or has been deleted.'
|
||||||
|
: error.message || 'We encountered an error loading this list. Please try again.'}
|
||||||
|
</p>
|
||||||
|
<div className="flex flex-col sm:flex-row gap-3">
|
||||||
|
{!isNotFound && (
|
||||||
|
<button
|
||||||
|
onClick={reset}
|
||||||
|
className="flex-1 px-4 py-3 bg-blue-500 hover:bg-blue-600 active:bg-blue-700 text-white rounded-lg transition-colors font-medium text-sm sm:text-base tap-target"
|
||||||
|
>
|
||||||
|
Try Again
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<Link
|
||||||
|
href="/"
|
||||||
|
className="flex-1 px-4 py-3 bg-gray-200 hover:bg-gray-300 active:bg-gray-400 text-gray-700 rounded-lg transition-colors font-medium text-sm sm:text-base tap-target text-center"
|
||||||
|
>
|
||||||
|
Back to Lists
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
55
app/list/[id]/item/[itemId]/error.tsx
Normal file
55
app/list/[id]/item/[itemId]/error.tsx
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import { useEffect } from 'react'
|
||||||
|
import { AlertTriangle } from 'lucide-react'
|
||||||
|
import { useRouter } from 'next/navigation'
|
||||||
|
|
||||||
|
export default function ItemError({
|
||||||
|
error,
|
||||||
|
reset,
|
||||||
|
}: {
|
||||||
|
error: Error & { digest?: string }
|
||||||
|
reset: () => void
|
||||||
|
}) {
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
console.error('Item page error:', error)
|
||||||
|
}, [error])
|
||||||
|
|
||||||
|
const isNotFound = error.message.includes('not found')
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center p-4 bg-gray-50">
|
||||||
|
<div className="max-w-md w-full bg-white rounded-lg shadow-lg p-6 sm:p-8">
|
||||||
|
<div className="flex items-center justify-center w-12 h-12 sm:w-16 sm:h-16 bg-red-100 rounded-full mx-auto mb-4">
|
||||||
|
<AlertTriangle className="w-6 h-6 sm:w-8 sm:h-8 text-red-600" />
|
||||||
|
</div>
|
||||||
|
<h2 className="text-xl sm:text-2xl font-bold text-gray-900 text-center mb-2">
|
||||||
|
{isNotFound ? 'Item Not Found' : 'Error Loading Item'}
|
||||||
|
</h2>
|
||||||
|
<p className="text-sm sm:text-base text-gray-600 text-center mb-6">
|
||||||
|
{isNotFound
|
||||||
|
? 'The item you are looking for does not exist or has been deleted.'
|
||||||
|
: error.message || 'We encountered an error loading this item. Please try again.'}
|
||||||
|
</p>
|
||||||
|
<div className="flex flex-col sm:flex-row gap-3">
|
||||||
|
{!isNotFound && (
|
||||||
|
<button
|
||||||
|
onClick={reset}
|
||||||
|
className="flex-1 px-4 py-3 bg-blue-500 hover:bg-blue-600 active:bg-blue-700 text-white rounded-lg transition-colors font-medium text-sm sm:text-base tap-target"
|
||||||
|
>
|
||||||
|
Try Again
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
onClick={() => router.back()}
|
||||||
|
className="flex-1 px-4 py-3 bg-gray-200 hover:bg-gray-300 active:bg-gray-400 text-gray-700 rounded-lg transition-colors font-medium text-sm sm:text-base tap-target"
|
||||||
|
>
|
||||||
|
Go Back
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
81
components/ErrorBoundary.tsx
Normal file
81
components/ErrorBoundary.tsx
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import React, { Component, ReactNode } from 'react'
|
||||||
|
import { AlertTriangle } from 'lucide-react'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
children: ReactNode
|
||||||
|
fallback?: ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
interface State {
|
||||||
|
hasError: boolean
|
||||||
|
error: Error | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ErrorBoundary extends Component<Props, State> {
|
||||||
|
constructor(props: Props) {
|
||||||
|
super(props)
|
||||||
|
this.state = { hasError: false, error: null }
|
||||||
|
}
|
||||||
|
|
||||||
|
static getDerivedStateFromError(error: Error): State {
|
||||||
|
return { hasError: true, error }
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
|
||||||
|
console.error('Error caught by boundary:', error, errorInfo)
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
if (this.state.hasError) {
|
||||||
|
if (this.props.fallback) {
|
||||||
|
return this.props.fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center p-4 bg-gray-50">
|
||||||
|
<div className="max-w-md w-full bg-white rounded-lg shadow-lg p-6 sm:p-8">
|
||||||
|
<div className="flex items-center justify-center w-12 h-12 sm:w-16 sm:h-16 bg-red-100 rounded-full mx-auto mb-4">
|
||||||
|
<AlertTriangle className="w-6 h-6 sm:w-8 sm:h-8 text-red-600" />
|
||||||
|
</div>
|
||||||
|
<h2 className="text-xl sm:text-2xl font-bold text-gray-900 text-center mb-2">
|
||||||
|
Something went wrong
|
||||||
|
</h2>
|
||||||
|
<p className="text-sm sm:text-base text-gray-600 text-center mb-6">
|
||||||
|
We encountered an unexpected error. Please try refreshing the page.
|
||||||
|
</p>
|
||||||
|
{this.state.error && (
|
||||||
|
<details className="mb-6 p-3 sm:p-4 bg-gray-50 rounded-lg text-xs sm:text-sm">
|
||||||
|
<summary className="cursor-pointer font-medium text-gray-700 mb-2">
|
||||||
|
Error details
|
||||||
|
</summary>
|
||||||
|
<pre className="text-red-600 overflow-auto whitespace-pre-wrap break-words">
|
||||||
|
{this.state.error.message}
|
||||||
|
</pre>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
<div className="flex flex-col sm:flex-row gap-3">
|
||||||
|
<button
|
||||||
|
onClick={() => window.location.reload()}
|
||||||
|
className="flex-1 px-4 py-3 bg-blue-500 hover:bg-blue-600 active:bg-blue-700 text-white rounded-lg transition-colors font-medium text-sm sm:text-base tap-target"
|
||||||
|
>
|
||||||
|
Refresh Page
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => window.location.href = '/'}
|
||||||
|
className="flex-1 px-4 py-3 bg-gray-200 hover:bg-gray-300 active:bg-gray-400 text-gray-700 rounded-lg transition-colors font-medium text-sm sm:text-base tap-target"
|
||||||
|
>
|
||||||
|
Go Home
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.props.children
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ErrorBoundary
|
||||||
317
lib/actions.ts
317
lib/actions.ts
@@ -3,8 +3,44 @@
|
|||||||
import { prisma } from './db'
|
import { prisma } from './db'
|
||||||
import { revalidatePath } from 'next/cache'
|
import { revalidatePath } from 'next/cache'
|
||||||
|
|
||||||
|
// Retry utility for database operations
|
||||||
|
async function retryOperation<T>(
|
||||||
|
operation: () => Promise<T>,
|
||||||
|
maxRetries: number = 3,
|
||||||
|
delayMs: number = 1000
|
||||||
|
): Promise<T> {
|
||||||
|
let lastError: Error | undefined
|
||||||
|
|
||||||
|
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
||||||
|
try {
|
||||||
|
return await operation()
|
||||||
|
} catch (error) {
|
||||||
|
lastError = error as Error
|
||||||
|
|
||||||
|
// Don't retry on validation errors or not found errors
|
||||||
|
if (
|
||||||
|
error instanceof Error &&
|
||||||
|
(error.message.includes('Unique constraint') ||
|
||||||
|
error.message.includes('Record to update not found') ||
|
||||||
|
error.message.includes('Record to delete does not exist'))
|
||||||
|
) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait before retrying (exponential backoff)
|
||||||
|
if (attempt < maxRetries - 1) {
|
||||||
|
await new Promise(resolve => setTimeout(resolve, delayMs * Math.pow(2, attempt)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw lastError
|
||||||
|
}
|
||||||
|
|
||||||
export async function getLists() {
|
export async function getLists() {
|
||||||
return await prisma.list.findMany({
|
try {
|
||||||
|
return await retryOperation(() =>
|
||||||
|
prisma.list.findMany({
|
||||||
include: {
|
include: {
|
||||||
items: true,
|
items: true,
|
||||||
},
|
},
|
||||||
@@ -12,21 +48,52 @@ export async function getLists() {
|
|||||||
updatedAt: 'desc',
|
updatedAt: 'desc',
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
)
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching lists:', error)
|
||||||
|
throw new Error('Failed to load lists. Please check your connection and try again.')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createList(title: string, color: string = '#3B82F6') {
|
export async function createList(title: string, color: string = '#3B82F6') {
|
||||||
const list = await prisma.list.create({
|
try {
|
||||||
|
// Validate input
|
||||||
|
if (!title || !title.trim()) {
|
||||||
|
throw new Error('List title is required')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (title.length > 200) {
|
||||||
|
throw new Error('List title must be less than 200 characters')
|
||||||
|
}
|
||||||
|
|
||||||
|
const list = await retryOperation(() =>
|
||||||
|
prisma.list.create({
|
||||||
data: {
|
data: {
|
||||||
title,
|
title: title.trim(),
|
||||||
color,
|
color,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
)
|
||||||
|
|
||||||
revalidatePath('/')
|
revalidatePath('/')
|
||||||
return list
|
return list
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error creating list:', error)
|
||||||
|
if (error instanceof Error && error.message.includes('required')) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
throw new Error('Failed to create list. Please try again.')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getListWithItems(listId: string) {
|
export async function getListWithItems(listId: string) {
|
||||||
return await prisma.list.findUnique({
|
try {
|
||||||
|
if (!listId) {
|
||||||
|
throw new Error('List ID is required')
|
||||||
|
}
|
||||||
|
|
||||||
|
const list = await retryOperation(() =>
|
||||||
|
prisma.list.findUnique({
|
||||||
where: { id: listId },
|
where: { id: listId },
|
||||||
include: {
|
include: {
|
||||||
items: {
|
items: {
|
||||||
@@ -36,15 +103,49 @@ export async function getListWithItems(listId: string) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!list) {
|
||||||
|
throw new Error('List not found')
|
||||||
|
}
|
||||||
|
|
||||||
|
return list
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching list:', error)
|
||||||
|
if (error instanceof Error && error.message === 'List not found') {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
throw new Error('Failed to load list. Please try again.')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getItem(itemId: string) {
|
export async function getItem(itemId: string) {
|
||||||
return await prisma.item.findUnique({
|
try {
|
||||||
|
if (!itemId) {
|
||||||
|
throw new Error('Item ID is required')
|
||||||
|
}
|
||||||
|
|
||||||
|
const item = await retryOperation(() =>
|
||||||
|
prisma.item.findUnique({
|
||||||
where: { id: itemId },
|
where: { id: itemId },
|
||||||
include: {
|
include: {
|
||||||
list: true,
|
list: true,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!item) {
|
||||||
|
throw new Error('Item not found')
|
||||||
|
}
|
||||||
|
|
||||||
|
return item
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching item:', error)
|
||||||
|
if (error instanceof Error && error.message === 'Item not found') {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
throw new Error('Failed to load item. Please try again.')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createItem(
|
export async function createItem(
|
||||||
@@ -58,10 +159,25 @@ export async function createItem(
|
|||||||
notes?: string | null
|
notes?: string | null
|
||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
const item = await prisma.item.create({
|
try {
|
||||||
|
// Validate input
|
||||||
|
if (!listId) {
|
||||||
|
throw new Error('List ID is required')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!title || !title.trim()) {
|
||||||
|
throw new Error('Item title is required')
|
||||||
|
}
|
||||||
|
|
||||||
|
if (title.length > 200) {
|
||||||
|
throw new Error('Item title must be less than 200 characters')
|
||||||
|
}
|
||||||
|
|
||||||
|
const item = await retryOperation(() =>
|
||||||
|
prisma.item.create({
|
||||||
data: {
|
data: {
|
||||||
title,
|
title: title.trim(),
|
||||||
description,
|
description: description?.trim() || null,
|
||||||
listId,
|
listId,
|
||||||
...(metadata?.priority && { priority: metadata.priority }),
|
...(metadata?.priority && { priority: metadata.priority }),
|
||||||
...(metadata?.dueDate !== undefined && { dueDate: metadata.dueDate }),
|
...(metadata?.dueDate !== undefined && { dueDate: metadata.dueDate }),
|
||||||
@@ -69,20 +185,49 @@ export async function createItem(
|
|||||||
...(metadata?.notes !== undefined && { notes: metadata.notes }),
|
...(metadata?.notes !== undefined && { notes: metadata.notes }),
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
)
|
||||||
|
|
||||||
revalidatePath(`/list/${listId}`)
|
revalidatePath(`/list/${listId}`)
|
||||||
return item
|
return item
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error creating item:', error)
|
||||||
|
if (error instanceof Error && (error.message.includes('required') || error.message.includes('must be'))) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
throw new Error('Failed to create item. Please try again.')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function toggleItem(itemId: string) {
|
export async function toggleItem(itemId: string) {
|
||||||
const item = await prisma.item.findUnique({ where: { id: itemId } })
|
try {
|
||||||
if (!item) return null
|
if (!itemId) {
|
||||||
|
throw new Error('Item ID is required')
|
||||||
|
}
|
||||||
|
|
||||||
const updated = await prisma.item.update({
|
const item = await retryOperation(() =>
|
||||||
|
prisma.item.findUnique({ where: { id: itemId } })
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!item) {
|
||||||
|
throw new Error('Item not found')
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await retryOperation(() =>
|
||||||
|
prisma.item.update({
|
||||||
where: { id: itemId },
|
where: { id: itemId },
|
||||||
data: { completed: !item.completed },
|
data: { completed: !item.completed },
|
||||||
})
|
})
|
||||||
|
)
|
||||||
|
|
||||||
revalidatePath(`/list/${item.listId}`)
|
revalidatePath(`/list/${item.listId}`)
|
||||||
return updated
|
return updated
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error toggling item:', error)
|
||||||
|
if (error instanceof Error && error.message === 'Item not found') {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
throw new Error('Failed to update item. Please try again.')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateItem(
|
export async function updateItem(
|
||||||
@@ -97,34 +242,114 @@ export async function updateItem(
|
|||||||
notes?: string | null
|
notes?: string | null
|
||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
const item = await prisma.item.findUnique({ where: { id: itemId } })
|
try {
|
||||||
if (!item) return null
|
if (!itemId) {
|
||||||
|
throw new Error('Item ID is required')
|
||||||
|
}
|
||||||
|
|
||||||
const updated = await prisma.item.update({
|
// Validate title if provided
|
||||||
|
if (data.title !== undefined) {
|
||||||
|
if (!data.title || !data.title.trim()) {
|
||||||
|
throw new Error('Item title cannot be empty')
|
||||||
|
}
|
||||||
|
if (data.title.length > 200) {
|
||||||
|
throw new Error('Item title must be less than 200 characters')
|
||||||
|
}
|
||||||
|
data.title = data.title.trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Trim description if provided
|
||||||
|
if (data.description !== undefined && data.description !== null) {
|
||||||
|
data.description = data.description.trim() || null
|
||||||
|
}
|
||||||
|
|
||||||
|
const item = await retryOperation(() =>
|
||||||
|
prisma.item.findUnique({ where: { id: itemId } })
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!item) {
|
||||||
|
throw new Error('Item not found')
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await retryOperation(() =>
|
||||||
|
prisma.item.update({
|
||||||
where: { id: itemId },
|
where: { id: itemId },
|
||||||
data,
|
data,
|
||||||
})
|
})
|
||||||
|
)
|
||||||
|
|
||||||
revalidatePath(`/list/${item.listId}`)
|
revalidatePath(`/list/${item.listId}`)
|
||||||
return updated
|
return updated
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error updating item:', error)
|
||||||
|
if (error instanceof Error && (error.message.includes('not found') || error.message.includes('required') || error.message.includes('cannot be'))) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
throw new Error('Failed to update item. Please try again.')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteItem(itemId: string) {
|
export async function deleteItem(itemId: string) {
|
||||||
const item = await prisma.item.findUnique({ where: { id: itemId } })
|
try {
|
||||||
if (!item) return null
|
if (!itemId) {
|
||||||
|
throw new Error('Item ID is required')
|
||||||
|
}
|
||||||
|
|
||||||
await prisma.item.delete({
|
const item = await retryOperation(() =>
|
||||||
|
prisma.item.findUnique({ where: { id: itemId } })
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!item) {
|
||||||
|
throw new Error('Item not found')
|
||||||
|
}
|
||||||
|
|
||||||
|
await retryOperation(() =>
|
||||||
|
prisma.item.delete({
|
||||||
where: { id: itemId },
|
where: { id: itemId },
|
||||||
})
|
})
|
||||||
|
)
|
||||||
|
|
||||||
revalidatePath(`/list/${item.listId}`)
|
revalidatePath(`/list/${item.listId}`)
|
||||||
return { success: true }
|
return { success: true }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error deleting item:', error)
|
||||||
|
if (error instanceof Error && error.message === 'Item not found') {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
throw new Error('Failed to delete item. Please try again.')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteList(listId: string) {
|
export async function deleteList(listId: string) {
|
||||||
await prisma.list.delete({
|
try {
|
||||||
|
if (!listId) {
|
||||||
|
throw new Error('List ID is required')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if list exists
|
||||||
|
const list = await retryOperation(() =>
|
||||||
|
prisma.list.findUnique({ where: { id: listId } })
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!list) {
|
||||||
|
throw new Error('List not found')
|
||||||
|
}
|
||||||
|
|
||||||
|
await retryOperation(() =>
|
||||||
|
prisma.list.delete({
|
||||||
where: { id: listId },
|
where: { id: listId },
|
||||||
})
|
})
|
||||||
|
)
|
||||||
|
|
||||||
revalidatePath('/')
|
revalidatePath('/')
|
||||||
return { success: true }
|
return { success: true }
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error deleting list:', error)
|
||||||
|
if (error instanceof Error && error.message === 'List not found') {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
throw new Error('Failed to delete list. Please try again.')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateList(
|
export async function updateList(
|
||||||
@@ -134,17 +359,44 @@ export async function updateList(
|
|||||||
color?: string
|
color?: string
|
||||||
}
|
}
|
||||||
) {
|
) {
|
||||||
const updated = await prisma.list.update({
|
try {
|
||||||
|
if (!listId) {
|
||||||
|
throw new Error('List ID is required')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate title if provided
|
||||||
|
if (data.title !== undefined) {
|
||||||
|
if (!data.title || !data.title.trim()) {
|
||||||
|
throw new Error('List title cannot be empty')
|
||||||
|
}
|
||||||
|
if (data.title.length > 200) {
|
||||||
|
throw new Error('List title must be less than 200 characters')
|
||||||
|
}
|
||||||
|
data.title = data.title.trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await retryOperation(() =>
|
||||||
|
prisma.list.update({
|
||||||
where: { id: listId },
|
where: { id: listId },
|
||||||
data,
|
data,
|
||||||
})
|
})
|
||||||
|
)
|
||||||
|
|
||||||
revalidatePath('/')
|
revalidatePath('/')
|
||||||
revalidatePath(`/list/${listId}`)
|
revalidatePath(`/list/${listId}`)
|
||||||
return updated
|
return updated
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error updating list:', error)
|
||||||
|
if (error instanceof Error && (error.message.includes('not found') || error.message.includes('required') || error.message.includes('cannot be'))) {
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
throw new Error('Failed to update list. Please try again.')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function searchItems(query: string, listId?: string) {
|
export async function searchItems(query: string, listId?: string) {
|
||||||
if (!query.trim()) {
|
try {
|
||||||
|
if (!query || !query.trim()) {
|
||||||
return []
|
return []
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,7 +431,8 @@ export async function searchItems(query: string, listId?: string) {
|
|||||||
whereClause.listId = listId
|
whereClause.listId = listId
|
||||||
}
|
}
|
||||||
|
|
||||||
const items = await prisma.item.findMany({
|
const items = await retryOperation(() =>
|
||||||
|
prisma.item.findMany({
|
||||||
where: whereClause,
|
where: whereClause,
|
||||||
include: {
|
include: {
|
||||||
list: true,
|
list: true,
|
||||||
@@ -188,16 +441,19 @@ export async function searchItems(query: string, listId?: string) {
|
|||||||
updatedAt: 'desc',
|
updatedAt: 'desc',
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
)
|
||||||
|
|
||||||
// Also search in tags (stored as JSON)
|
// Also search in tags (stored as JSON)
|
||||||
const allItems = listId
|
const allItems = await retryOperation(() =>
|
||||||
? await prisma.item.findMany({
|
listId
|
||||||
|
? prisma.item.findMany({
|
||||||
where: { listId },
|
where: { listId },
|
||||||
include: { list: true },
|
include: { list: true },
|
||||||
})
|
})
|
||||||
: await prisma.item.findMany({
|
: prisma.item.findMany({
|
||||||
include: { list: true },
|
include: { list: true },
|
||||||
})
|
})
|
||||||
|
)
|
||||||
|
|
||||||
const tagMatches = allItems.filter((item) => {
|
const tagMatches = allItems.filter((item) => {
|
||||||
const tags = Array.isArray(item.tags) ? item.tags : []
|
const tags = Array.isArray(item.tags) ? item.tags : []
|
||||||
@@ -213,6 +469,10 @@ export async function searchItems(query: string, listId?: string) {
|
|||||||
)
|
)
|
||||||
|
|
||||||
return uniqueResults
|
return uniqueResults
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error searching items:', error)
|
||||||
|
throw new Error('Failed to search items. Please try again.')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getItemsByFilter(
|
export async function getItemsByFilter(
|
||||||
@@ -226,6 +486,7 @@ export async function getItemsByFilter(
|
|||||||
sortOrder?: 'asc' | 'desc'
|
sortOrder?: 'asc' | 'desc'
|
||||||
} = {}
|
} = {}
|
||||||
) {
|
) {
|
||||||
|
try {
|
||||||
// Build the where clause with compound filters (AND logic)
|
// Build the where clause with compound filters (AND logic)
|
||||||
const whereClause: any = {}
|
const whereClause: any = {}
|
||||||
|
|
||||||
@@ -259,12 +520,14 @@ export async function getItemsByFilter(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fetch items from database
|
// Fetch items from database
|
||||||
const items = await prisma.item.findMany({
|
const items = await retryOperation(() =>
|
||||||
|
prisma.item.findMany({
|
||||||
where: whereClause,
|
where: whereClause,
|
||||||
include: {
|
include: {
|
||||||
list: true,
|
list: true,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
)
|
||||||
|
|
||||||
// Filter by tags (client-side since tags are stored as JSON)
|
// Filter by tags (client-side since tags are stored as JSON)
|
||||||
let filteredItems = items
|
let filteredItems = items
|
||||||
@@ -315,4 +578,8 @@ export async function getItemsByFilter(
|
|||||||
})
|
})
|
||||||
|
|
||||||
return sortedItems
|
return sortedItems
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error filtering items:', error)
|
||||||
|
throw new Error('Failed to filter items. Please try again.')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
18
lib/db.ts
18
lib/db.ts
@@ -4,6 +4,22 @@ const globalForPrisma = globalThis as unknown as {
|
|||||||
prisma: PrismaClient | undefined
|
prisma: PrismaClient | undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
export const prisma = globalForPrisma.prisma ?? new PrismaClient()
|
// Create Prisma client with connection error handling
|
||||||
|
export const prisma = globalForPrisma.prisma ?? new PrismaClient({
|
||||||
|
log: process.env.NODE_ENV === 'development' ? ['error', 'warn'] : ['error'],
|
||||||
|
})
|
||||||
|
|
||||||
|
// Handle connection errors
|
||||||
|
prisma.$connect().catch((error) => {
|
||||||
|
console.error('Failed to connect to database:', error)
|
||||||
|
// Don't throw here - let individual queries handle connection errors
|
||||||
|
})
|
||||||
|
|
||||||
|
// Graceful shutdown
|
||||||
|
if (typeof window === 'undefined') {
|
||||||
|
process.on('beforeExit', async () => {
|
||||||
|
await prisma.$disconnect()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
|
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
|
||||||
Reference in New Issue
Block a user