prenez-le-train/server/cli/import.js

44 lines
1.6 KiB
JavaScript
Raw Permalink Normal View History

2023-08-11 16:07:34 +00:00
const fs = require('fs')
const db = require("../models")
const Airport = db['Airport']
const Flight = db['Flight']
2023-08-11 17:14:36 +00:00
db.sequelize.sync().then(() => (async () => {
// Refresh airport data
let airportData = await fs.promises.readFile(`${__dirname}/../data/airports.json`, 'utf-8')
airportData = JSON.parse(airportData)
2023-08-11 16:07:34 +00:00
2023-08-11 17:14:36 +00:00
let icao_codes = []
let iata_codes = []
let results = await Airport.findAll({attributes: ['icao_code', 'iata_code']})
for (let result of results) {
if (result.icao_code)
icao_codes.push(result.icao_code)
if (result.iata_code)
iata_codes.push(result.iata_code)
2023-08-11 16:07:34 +00:00
}
2023-08-11 17:14:36 +00:00
// Import all not-imported airports
await Airport.bulkCreate(airportData['response'].filter(airport => !icao_codes.includes(airport.icao_code)
&& !iata_codes.includes(airport.iata_code)))
2023-08-11 16:07:34 +00:00
2023-08-11 17:14:36 +00:00
// Import flight routes per departure
let airports = await Airport.findAll({attributes: ['icao_code']})
for (let airport of airports) {
const airportRoutesFile = `${__dirname}/../data/routes/${airport.icao_code}.json`
// Ignore unexisting files
if (!(await fs.promises.stat(airportRoutesFile).catch(() => false)))
continue
2023-08-11 16:07:34 +00:00
2023-08-11 17:14:36 +00:00
// Read routes
let flightsData = await fs.promises.readFile(airportRoutesFile, 'utf-8')
flightsData = JSON.parse(flightsData)
2023-08-11 16:07:34 +00:00
2023-08-11 17:14:36 +00:00
// First remove old routes
await Flight.destroy({where: {dep_icao: airport.icao_code}})
// Then import new routes
await Flight.bulkCreate(flightsData['response'])
}
})())