EpisodesController.ts 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
  2. import Episode from 'App/Models/Episode'
  3. import PaginationService from 'App/Services/PaginationService'
  4. import { schema } from '@ioc:Adonis/Core/Validator'
  5. import Decimal from 'decimal.js'
  6. import Order from 'App/Models/Order'
  7. export default class EpisodesController {
  8. private paginationService = new PaginationService(Episode)
  9. public async index({ request }: HttpContextContract) {
  10. return await this.paginationService.paginate(request.all())
  11. }
  12. public async store({ request }: HttpContextContract) {
  13. const data: any = await request.validate({
  14. schema: schema.create({
  15. seriesId: schema.number(),
  16. title: schema.string.optional(),
  17. episodeNum: schema.number(),
  18. description: schema.string.optional(),
  19. cover: schema.string.optional(),
  20. video: schema.string.optional(),
  21. playCount: schema.number.optional(),
  22. price: schema.string.optional()
  23. })
  24. })
  25. if (data.price) {
  26. data.price = new Decimal(data.price)
  27. }
  28. return await Episode.create(data)
  29. }
  30. public async show({ params, auth }: HttpContextContract) {
  31. const episode = await Episode.findOrFail(params.id)
  32. if (episode.price.eq(0)) {
  33. episode.purchased = true
  34. } else if (auth.user) {
  35. let order = await Order.query()
  36. .where('userId', auth.user.id)
  37. .where('type', 'series')
  38. .where('seriesId', episode.seriesId)
  39. .first()
  40. if (!order) {
  41. order = await Order.query()
  42. .where('userId', auth.user.id)
  43. .where('type', 'episode')
  44. .where('episodeId', episode.id)
  45. .first()
  46. }
  47. if (order) {
  48. episode.purchased = true
  49. }
  50. }
  51. return episode
  52. }
  53. public async update({ request, params }: HttpContextContract) {
  54. const data: any = await request.validate({
  55. schema: schema.create({
  56. seriesId: schema.number.optional(),
  57. title: schema.string.optional(),
  58. episodeNum: schema.number.optional(),
  59. description: schema.string.optional(),
  60. cover: schema.string.optional(),
  61. video: schema.string.optional(),
  62. playCount: schema.number.optional(),
  63. price: schema.number.optional()
  64. })
  65. })
  66. if (data.price) {
  67. data.price = new Decimal(data.price)
  68. }
  69. const episode = await Episode.findOrFail(params.id)
  70. episode.merge(data)
  71. return await episode.save()
  72. }
  73. public async destroy({ params }: HttpContextContract) {
  74. const episode = await Episode.findOrFail(params.id)
  75. await episode.delete()
  76. }
  77. }