Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Development #3

Merged
merged 8 commits into from
Apr 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
node_modules/
dataSources/
.env
7 changes: 7 additions & 0 deletions assets/AppStrings.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const AppStrings = {
"user-already-exists-err-msg": "User with email address already exists",
"user-no-admin-access-err-msg": "Need admin access",
"user-not-logged-in": "You're not logged in",

"airline-already-exists-err-msg": "Airline already exists"
}
43 changes: 43 additions & 0 deletions controllers/AirlinesControllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { User } from "../models/UsersModel"
import { Airline } from "../models/AirlinesModel"
import { AppStrings } from "../assets/AppStrings"

export const AddAirline = async(req, res) => {
const { userId, admin, IATA, ICAO, name, country } = req.body

// TODO: AUTH implementation
if(!admin){
res.send(AppStrings["user-no-admin-access-err-msg"])
}

else{
const accessingUser = await User.findById(userId)

if(accessingUser){
const existingAirline = await Airline.find({ $and: [{ name }, { country }]}).exec()

if(existingAirline.length){
res.send(AppStrings["airline-already-exists-err-msg"])
}
else{
const NewAirline = new Airline({
IATA,
ICAO,
name: name.toUpperCase(),
country: country.toUpperCase()
})

NewAirline.save((err, SavedAirline) => {
if(err){
res.send(err)
}
res.json(SavedAirline)
})
}
}
else{
res.send(AppStrings["user-not-logged-in"])
}

}
}
81 changes: 74 additions & 7 deletions controllers/FlightsControllers.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,82 @@
export const GetFlights = async(req, res) => {
import axios from "axios"
import dayjs from "dayjs"
import dotenv from "dotenv";

import { asyncMap } from "../helpers"

dotenv.config();
export const GetFlights = async (req, res) => {

try {

} catch(e){
console.log(e)
} catch (e) {
res.send(e);
}
}
};

export const AddNewFlight = async(req, res) => {
export const AddNewFlight = async (req, res) => {
const { flightNumber, flightDate } = req.body
try {
const flightDateDayJsObject = dayjs(flightDate).toISOString()

// Flightaware API calls to fetch aircraft registration based on the flight number
const flightsWithThisFlightNumberData = await axios.get(`${process.env.FLIGHTAWARE_API_DOMAIN}/flights/${flightNumber.toUpperCase()}`, { headers: {"x-apikey": process.env.FLIGHTAWARE_API_KEY } })

const flightsWithThisFlightNumber = flightsWithThisFlightNumberData.data.flights.filter((flight) => dayjs(flight.scheduled_out).isSame(flightDateDayJsObject, "day"))

const flightInformation = await asyncMap(flightsWithThisFlightNumber, async({ registration, scheduled_out, scheduled_in, status, progress_percent }) => {
const aircraftRegistration = registration

let aircraftImageResponse = []
if(aircraftRegistration !== null){
// Get aircraft picture
const flickrUrl = `${process.env.FLICKR_PHOTO_SEARCH_URL}&text=${aircraftRegistration}`

const aircraftPhotosReq = await axios.get(flickrUrl)

const aircraftPhotos = aircraftPhotosReq.data.photos.photo
const numOfPhotos = aircraftPhotos.length

let photosToConsider = []

// If there are more than 5 pictures, only show 5
// If less than 5, make sure there are atleast 2 and show them
// Else show the last image

if(numOfPhotos > 5){
photosToConsider = aircraftPhotos.slice(0,5)
}
if(numOfPhotos >= 2 && numOfPhotos < 5){
photosToConsider = aircraftPhotos.slice(0,2)
}

if(numOfPhotos < 2){
photosToConsider = [aircraftPhotos[numOfPhotos-1]]
}

aircraftImageResponse = photosToConsider.map(({ server, id, secret, title }) => {
const aircraftPhotoURL = `${process.env.FLICKR_PHOTO_URL}/${server}/${id}_${secret}.jpg`

return {
aircraftPhotoURL,
aircraftPhotoTitle: title
}
})
}

return {
aircraftRegistration,
status,
scheduledOut: scheduled_out,
scheduledIn: scheduled_in,
progressPercent: progress_percent,
aircraftImageResponse
}
})

} catch(e){
res.send(flightInformation)
} catch (e) {
console.log(e)
res.send(e)
}
}
};
30 changes: 30 additions & 0 deletions controllers/UsersController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import mongoose from "mongoose"
import { AppStrings } from "../assets/AppStrings"
import { User } from "../models/UsersModel"

export const SignUpUser = async(req, res) => {
const { firstName, lastName, email } = req.body

const existingUser = await User.find({ email: email }).exec()
console.log(existingUser)

if(existingUser){
res.send(AppStrings["user-already-exists-err-msg"])
}

else{
const NewUser = new User({
firstName,
lastName,
email
})

NewUser.save((err, User) => {
if(err){
res.send(err)
}
res.json(User)
})
}

}
11 changes: 0 additions & 11 deletions database/database.sql

This file was deleted.

12 changes: 0 additions & 12 deletions dbConnection.js

This file was deleted.

14 changes: 14 additions & 0 deletions helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export const asyncForEach = async (arr, callback) => {
for (let index = 0; index < arr.length; index += 1) {
await callback(arr[index], index, arr);
}
};

export const asyncMap = async (array = [], callback) => {
const resultArray = [];
for (let index = 0; index < array.length; index++) {
const mappedValue = await callback(array[index], index, array);
resultArray[index] = mappedValue;
}
return resultArray;
};
66 changes: 48 additions & 18 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,55 @@
import express from 'express'
import mongoose from 'mongoose'
import bodyparser from 'body-parser'
import cors from 'cors'
import dotenv from 'dotenv'
import { pool } from "./dbConnection"
import { routes } from "./routes/appRoutes"
import express from "express";
import mongoose from "mongoose";
import bodyparser from "body-parser";
import cors from "cors";
import dotenv from "dotenv";

dotenv.config()
import { checkJwtAuth } from "./middlewares/auth"
import { routes } from "./routes/appRoutes";

const app = express()
import { createUsers } from "./migration/createUsers"
import { ImportAirports } from "./migration/importAirports"
import { ImportAirlines } from "./migration/importAirlines"

app.use(bodyparser.urlencoded({
extended: true
}))
dotenv.config();

app.use(bodyparser.json())
const app = express();

app.use(cors())
mongoose.connect(`mongodb://${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}`,{
useNewUrlParser: true,
useUnifiedTopology: true
})

routes(app)

app.listen(process.env.SERVER_PORT, () => {
console.log("Server running on port 3000")
})
app.use(
bodyparser.urlencoded({
extended: true
})
);

app.use(bodyparser.json());

app.use(cors());

app.use(checkJwtAuth);

routes(app);

app.listen(process.env.SERVER_PORT, async() => {
console.log(`Server running on port ${process.env.SERVER_PORT}`);

// Run to create users
// console.log("Creating user(s)")
// await createUsers()
// console.log("Finished creating users")

// Run to ingest airports data (Just USA for now)
// console.log("Initiating Airports Data load")
// await ImportAirports()
// console.log("Finished Airports Data Load")

// Run to ingest airlines data (Just USA for now)
// console.log("Initiating Airlines Data load")
// await ImportAirlines()
// console.log("Finished Airlines Data Load")
});
19 changes: 19 additions & 0 deletions middlewares/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import jwt from "express-jwt";
import jwksRsa from "jwks-rsa"
import dotenv from "dotenv";

dotenv.config();

export const checkJwtAuth = jwt({
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`
}),

// Validate the audience and the issuer.
audience: `https://${process.env.AUTH0_IDENTIFIER}`,
issuer: `https://${process.env.AUTH0_DOMAIN}/`,
algorithms: [`${process.env.AUTH0_ALGORITHM}`]
});
24 changes: 24 additions & 0 deletions migration/createUsers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import mongoose from "mongoose"
import { User } from "../models/UsersModel"
import { asyncForEach } from "../helpers"

const usersToAdd = []

export const createUsers = async() => {
await asyncForEach(usersToAdd, async({ firstName, lastName, email }) => {
const UserToSave = new User({
firstName,
lastName,
email
})

UserToSave.save((err, UserSaved) => {
if(err){
console.error(err)
}
return UserSaved
})
})

return 1
}
33 changes: 33 additions & 0 deletions migration/importAirlines.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import mongoose from "mongoose"
import axios from "axios"
import dotenv from "dotenv";
import { Airline } from "../models/AirlinesModel"
import { AirlinesUsaData } from "../dataSources/AirlinesUsaData"
import { asyncForEach } from "../helpers"

dotenv.config();

export const ImportAirlines = async() => {
const inputData = AirlinesUsaData

await asyncForEach(inputData, async({ Name, IATA, ICAO, Country, Active }) => {
const active = Active === "Y" ? true : false

const AirlineToSave = new Airline({
ICAO: ICAO.toUpperCase(),
IATA: IATA.toUpperCase(),
name: Name.toUpperCase(),
country: Country.toLowerCase(),
active
})

AirlineToSave.save((err, AirlineSaved) => {
if(err){
console.error(err)
}
return AirlineSaved
})
})

return 1
}
Loading