62 lines
1.7 KiB
TypeScript
62 lines
1.7 KiB
TypeScript
import { getDatabase } from '~/server/utils/database.server'
|
|
import { verifyJWT } from '~/server/utils/auth'
|
|
|
|
const generateSlug = (title: string, date: string) => {
|
|
if (!title || !date) return ''
|
|
|
|
const formattedTitle = title
|
|
.toLowerCase()
|
|
.replace(/[^a-z0-9\s-]/g, '')
|
|
.replace(/\s+/g, '-')
|
|
.replace(/-+/g, '-')
|
|
.trim()
|
|
|
|
const dateObj = new Date(date)
|
|
const month = String(dateObj.getMonth() + 1).padStart(2, '0')
|
|
const day = String(dateObj.getDate()).padStart(2, '0')
|
|
const year = dateObj.getFullYear()
|
|
|
|
return `sermon-${month}${day}${year}`
|
|
}
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const db = await getDatabase()
|
|
|
|
const body = await readBody(event)
|
|
const { title, date, bibleReferences, personalApplication, pastorChallenge } = body
|
|
|
|
if (!title || !date) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: 'Title and date are required'
|
|
})
|
|
}
|
|
|
|
const slug = generateSlug(title, date)
|
|
|
|
try {
|
|
const result = db.prepare(`
|
|
INSERT INTO sermons (title, date, slug, bible_references, personal_application, pastor_challenge)
|
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
`).run(title, date, slug, JSON.stringify(bibleReferences || []), personalApplication || '', pastorChallenge || '')
|
|
|
|
return {
|
|
id: result.lastInsertRowid,
|
|
title,
|
|
date,
|
|
slug,
|
|
bibleReferences: bibleReferences || [],
|
|
personalApplication: personalApplication || '',
|
|
pastorChallenge: pastorChallenge || ''
|
|
}
|
|
} catch (error: any) {
|
|
if (error.code === 'SQLITE_CONSTRAINT_UNIQUE') {
|
|
throw createError({
|
|
statusCode: 409,
|
|
statusMessage: 'A sermon with this date already exists'
|
|
})
|
|
}
|
|
throw error
|
|
}
|
|
})
|