ThemeController.js

125 lines | 2.739 kB Blame History Raw Download
'use strict'

/** @typedef {import('@adonisjs/framework/src/Request')} Request */
/** @typedef {import('@adonisjs/framework/src/Response')} Response */
/** @typedef {import('@adonisjs/framework/src/View')} View */

const Theme = use('App/Models/Theme')
const { validate } = use('Validator')

/**
 * Resourceful controller for interacting with themes
 */
class ThemeController {
  /**
   * Show a list of all themes.
   * GET themes
   *
   * @param {object} ctx
   * @param {Request} ctx.request
   * @param {Response} ctx.response
   * @param {View} ctx.view
   */
  async index ({ request, response, view }) {
    const themes = await Theme.query().orderBy('name', 'asc').fetch()
  
    return view.render('themes.index', {
      themes: themes.toJSON()
    })
  }

  /**
   * Render a form to be used for creating a new theme.
   * GET themes/create
   *
   * @param {object} ctx
   * @param {Request} ctx.request
   * @param {Response} ctx.response
   * @param {View} ctx.view
   */
  async create ({ request, response, view }) {
    return view.render('themes.create')
  }

  /**
   * Create/save a new theme.
   * POST themes
   *
   * @param {object} ctx
   * @param {Request} ctx.request
   * @param {Response} ctx.response
   */
  async store ({ session, request, response }) { 

    const data = request.only(['name'])

    const validation = await validate(request.all(), {
      name: 'required|max:255',
    }, {
      'name.required': `Theme name is required`,
    })

    if(validation.fails()) {
      session.withErrors(validation.messages()).flashAll()
      return response.redirect('back')
    }

    await Theme.create(data)

    return response.redirect('/themes')

  }

  /**
   * Display a single theme.
   * GET themes/:id
   *
   * @param {object} ctx
   * @param {Request} ctx.request
   * @param {Response} ctx.response
   * @param {View} ctx.view
   */
  async show ({ params, request, response, view }) {
  }

  /**
   * Render a form to update an existing theme.
   * GET themes/:id/edit
   *
   * @param {object} ctx
   * @param {Request} ctx.request
   * @param {Response} ctx.response
   * @param {View} ctx.view
   */
  async edit ({ params, request, response, view }) {
  }

  /**
   * Update theme details.
   * PUT or PATCH themes/:id
   *
   * @param {object} ctx
   * @param {Request} ctx.request
   * @param {Response} ctx.response
   */
  async update ({ params, request, response }) {
  }

  /**
   * Delete a theme with id.
   * DELETE themes/:id
   *
   * @param {object} ctx
   * @param {Request} ctx.request
   * @param {Response} ctx.response
   */
  async destroy ({ params, request, response }) {
    const theme = await Theme.findOrFail(params.id)
    await theme.delete()

    return response.redirect('/themes')
  }
}

module.exports = ThemeController