2023-06-23 13:13:22 +00:00
|
|
|
const express = require("express")
|
|
|
|
const path = require("path")
|
2023-06-19 13:19:32 +00:00
|
|
|
|
2023-06-23 13:13:22 +00:00
|
|
|
const db = require("./models")
|
|
|
|
const Airport = db['Airport']
|
|
|
|
const Flight = db['Flight']
|
2023-06-19 13:19:32 +00:00
|
|
|
|
2023-06-23 13:13:22 +00:00
|
|
|
db.sequelize.sync().then(() => console.log("DB synced."))
|
2023-06-19 13:19:32 +00:00
|
|
|
|
2023-06-23 13:13:22 +00:00
|
|
|
const PORT = process.env.PORT || 3001
|
|
|
|
|
|
|
|
const app = express()
|
|
|
|
|
|
|
|
app.use(express.static(path.resolve(__dirname, '../client/build')))
|
|
|
|
app.use(express.json())
|
2023-06-19 13:19:32 +00:00
|
|
|
|
|
|
|
app.get("/api", (req, res) => {
|
2023-06-23 13:13:22 +00:00
|
|
|
res.json({ message: "Hello from server!" })
|
|
|
|
})
|
|
|
|
|
|
|
|
app.get("/api/airports", (req, res) => {
|
2023-08-11 17:48:50 +00:00
|
|
|
const search = req.query.search.toLowerCase()
|
|
|
|
let where = {}
|
|
|
|
if (search) {
|
|
|
|
let or_array = []
|
|
|
|
for (let col_name of ['name', 'icao_code', 'iata_code'])
|
|
|
|
or_array.push(db.sequelize.where(db.sequelize.fn('lower', db.sequelize.col(col_name)),
|
|
|
|
{[db.Sequelize.Op.like]: `%${search}%`}))
|
|
|
|
where = {[db.Sequelize.Op.or]: or_array}
|
|
|
|
}
|
|
|
|
Airport.findAll({where: where}).then(airports => res.json(airports))
|
2023-06-23 13:13:22 +00:00
|
|
|
})
|
|
|
|
|
2023-08-11 17:48:50 +00:00
|
|
|
app.get("/api/airport/:icao_code", (req, res) => {
|
|
|
|
const icao_code = req.params.icao_code
|
|
|
|
Airport.findOne({where: {icao_code: icao_code}}).then(data => {
|
2023-06-23 13:13:22 +00:00
|
|
|
if (data)
|
|
|
|
res.json(data)
|
|
|
|
else
|
|
|
|
res.status(404).json({message: `Cannot find airport with id=${id}`})
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
|
|
|
app.get("/api/flights/:dep_icao", (req, res) => {
|
|
|
|
const dep_icao = req.params.dep_icao
|
|
|
|
Flight.findAll({where: {dep_icao: dep_icao}}).then(data => {
|
|
|
|
if (data)
|
|
|
|
res.json(data)
|
|
|
|
else
|
|
|
|
res.status(500).json({message: `An error occurred while fetching flights.`})
|
|
|
|
})
|
|
|
|
})
|
2023-06-19 13:19:32 +00:00
|
|
|
|
2023-08-11 17:48:50 +00:00
|
|
|
app.get("/api/flights/:dep_icao/:arr_icao", (req, res) => {
|
|
|
|
const dep_icao = req.params.dep_icao
|
|
|
|
const arr_icao = req.params.arr_icao
|
|
|
|
Flight.findAll({where: {dep_icao: dep_icao, arr_icao: arr_icao}}).then(data => {
|
|
|
|
if (data)
|
|
|
|
res.json(data)
|
|
|
|
else
|
|
|
|
res.status(500).json({message: `An error occurred while fetching flights.`})
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
2023-06-19 13:19:32 +00:00
|
|
|
app.get('*', (req, res) => {
|
2023-06-23 13:13:22 +00:00
|
|
|
res.sendFile(path.resolve(__dirname, '../client/build', req.path))
|
|
|
|
})
|
2023-06-19 13:19:32 +00:00
|
|
|
|
|
|
|
app.listen(PORT, () => {
|
2023-06-23 13:13:22 +00:00
|
|
|
console.log(`Server listening on ${PORT}`)
|
|
|
|
})
|