BannersController.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
  2. import Banner from 'App/Models/Banner'
  3. import PaginationService from 'App/Services/PaginationService'
  4. import { schema } from '@ioc:Adonis/Core/Validator'
  5. export default class BannersController {
  6. private paginationService = new PaginationService(Banner)
  7. public async index({ request }: HttpContextContract) {
  8. const { page, perPage } = request.qs()
  9. const pagination = await this.paginationService.paginate(request.all())
  10. return pagination
  11. }
  12. public async store({ request, bouncer }: HttpContextContract) {
  13. await bouncer.authorize('admin')
  14. const validationSchema = schema.create({
  15. title: schema.string(),
  16. img: schema.string(),
  17. link: schema.string.optional(),
  18. desc: schema.string.optional()
  19. })
  20. const validatedData = await request.validate({
  21. schema: validationSchema
  22. })
  23. const banner = await Banner.create(validatedData)
  24. return banner
  25. }
  26. public async show({ params }: HttpContextContract) {
  27. const banner = await Banner.findOrFail(params.id)
  28. return banner
  29. }
  30. public async update({ request, params, bouncer }: HttpContextContract) {
  31. await bouncer.authorize('admin')
  32. const validationSchema = schema.create({
  33. title: schema.string.optional(),
  34. img: schema.string.optional(),
  35. link: schema.string.optional(),
  36. desc: schema.string.optional()
  37. })
  38. const validatedData = await request.validate({
  39. schema: validationSchema
  40. })
  41. const banner = await Banner.findOrFail(params.id)
  42. banner.merge(validatedData)
  43. await banner.save()
  44. return banner
  45. }
  46. public async destroy({ params, bouncer }: HttpContextContract) {
  47. await bouncer.authorize('admin')
  48. const banner = await Banner.findOrFail(params.id)
  49. await banner.delete()
  50. }
  51. }