|
| 1 | +import { HttpContext } from '@adonisjs/core/http' |
| 2 | +import { articleValidator } from '#validators/article_validator' |
| 3 | +import Article from '#models/article' |
| 4 | +import { DateTime } from 'luxon' |
| 5 | + |
| 6 | +export default class ArticlesController { |
| 7 | + async index({ inertia, request }: HttpContext) { |
| 8 | + const page = request.input('page', 1) |
| 9 | + const articles = await Article.query() |
| 10 | + .preload('author') |
| 11 | + .where('is_published', true) |
| 12 | + .orderBy('published_at', 'desc') |
| 13 | + .paginate(page, 10) |
| 14 | + |
| 15 | + return inertia.render('articles/index', { |
| 16 | + articles: articles.toJSON(), |
| 17 | + }) |
| 18 | + } |
| 19 | + |
| 20 | + async create({ inertia }: HttpContext) { |
| 21 | + return inertia.render('articles/create') |
| 22 | + } |
| 23 | + |
| 24 | + async store({ request, auth, response }: HttpContext) { |
| 25 | + const data = await articleValidator.validate(request.all()) |
| 26 | + const article = new Article() |
| 27 | + |
| 28 | + article.title = data.title |
| 29 | + article.content = data.content |
| 30 | + article.excerpt = data.excerpt |
| 31 | + article.isPublished = data.isPublished || false |
| 32 | + article.authorId = auth.user!.id |
| 33 | + if (data.isPublished) { |
| 34 | + article.publishedAt = DateTime.now() |
| 35 | + } |
| 36 | + |
| 37 | + await article.generateSlug() |
| 38 | + await article.save() |
| 39 | + |
| 40 | + return response.redirect().toRoute('articles.show', { slug: article.slug }) |
| 41 | + } |
| 42 | + |
| 43 | + async show({ inertia, params }: HttpContext) { |
| 44 | + const article = await Article.query().where('slug', params.slug).preload('author').firstOrFail() |
| 45 | + |
| 46 | + return inertia.render('articles/[slug]', { article }) |
| 47 | + } |
| 48 | +} |
0 commit comments