ATC_SIMPLE/BACKEND/app/controllers/stations_controller.ts

77 lines
2.5 KiB
TypeScript

import type { HttpContext } from '@adonisjs/core/http'
import Station from '#models/station'
export default class StationsController {
public async index({}: HttpContext) {
return await Station.query().preload('lines')
}
public async store({ request, response }: HttpContext) {
let payload = request.only(Array.from(Station.$columnsDefinitions.keys()))
try {
const stationName = await Station.findBy('name', payload.name)
if (stationName) return response.status(400).json({ message: 'Station name exist!' })
const stationIP = await Station.findBy('ip', payload.ip)
if (stationIP) return response.status(400).json({ message: 'Ip of station is exist!' })
const station = await Station.create(payload)
return response.created({
status: true,
message: 'Station created successfully',
data: station,
})
} catch (error) {
return response.badRequest({ error: error, message: 'Station create failed', status: false })
}
}
public async show({ params }: HttpContext) {
return await Station.findOrFail(params.id)
}
public async update({ request, response }: HttpContext) {
let payload = request.only(
Array.from(Station.$columnsDefinitions.keys()).filter(
(f) => f !== 'created_at' && f !== 'updated_at'
)
)
try {
const station = await Station.find(request.body().id)
// If the station does not exist, return a 404 response
if (!station) {
return response.status(404).json({ message: 'Station not found' })
}
Object.assign(station, payload)
await station.save()
return response.ok({ status: true, message: 'Station update successfully', data: station })
} catch (error) {
return response.badRequest({ error: error, message: 'Station update failed', status: false })
}
}
public async destroy({ request, response }: HttpContext) {
try {
const station = await Station.find(request.body().id)
// If the station does not exist, return a 404 response
if (!station) {
return response.status(404).json({ message: 'Station not found' })
}
// Optionally, delete associated lines first
await station.related('lines').query().delete()
// Delete the station
await station.delete()
return response.ok({ status: true, message: 'Station delete successfully', data: station })
} catch (error) {
return response.badRequest({ error: error, message: 'Station delete failed', status: false })
}
}
}