Builds live flight data widget

This commit is contained in:
Alicia Sykes 2021-12-14 00:55:01 +00:00
parent 5cb588a586
commit 642cfc655b
4 changed files with 244 additions and 2 deletions

View File

@ -109,12 +109,21 @@ Keep track of price changes of your favorite crypto assets. Data is fetched from
**Field** | **Type** | **Required** | **Description**
--- | --- | --- | ---
**`assets`** | `string` | Required | An array of cryptocurrencies, coins and tokens. See [list of supported assets](https://api.coingecko.com/api/v3/asset_platforms)
**`assets`** | `string` | _Optional_ | An array of cryptocurrencies, coins and tokens. See [list of supported assets](https://api.coingecko.com/api/v3/asset_platforms). If none are specified, then the top coins by `sortBy` (defaults to market cap) will be returned
**`currency`** | `string` | _Optional_ | The fiat currency to display price in, expressed as an ISO-4217 alpha code (see [list of currencies](https://www.iban.com/currency-codes)). Defaults to `USD`
**`sortBy`** | `number` | _Optional_ | The method of sorting results. Can be `marketCap`, `volume` or `alphabetical`. Defaults to `marketCap`.
**`sortBy`** | `string` | _Optional_ | The method of sorting results. Can be `marketCap`, `volume` or `alphabetical`. Defaults to `marketCap`.
**`limit`** | `number` | _Optional_ | Number of results to return, useful when no assets are specified. Defaults to either `all` or `100`
##### Example
```yaml
- type: crypto-watch-list
options:
limit: 10
```
Or
```yaml
- type: crypto-watch-list
options:
@ -279,6 +288,32 @@ Renders a programming or generic joke. Data is fetched from the [JokesAPI](https
category: Programming
```
### Flight Data
Displays airport departure and arrival flights, using data from [AeroDataBox](https://www.aerodatabox.com/). Useful if you live near an airport and often wonder where the flight overhead is going to. Hover over a row for more flight data.
<p align="center"><img width="400" src="https://i.ibb.co/yPMBJSY/flight-data.png" /></p>
##### Options
**Field** | **Type** | **Required** | **Description**
--- | --- | --- | ---
**`airport`** | `string` | Required | The airport to show flight data from. Should be specified as a 4-character ICAO-code, a full list of which can be found [here](https://en.wikipedia.org/wiki/ICAO_airport_code) (example: `KBJC` or `EGKK`)
**`apiKey`** | `string` | Required | A valid [RapidAPI](https://rapidapi.com/) Key, with [AeroDataBox](https://rapidapi.com/aerodatabox/api/aerodatabox/) enabled (check in your [Subscription Dashboard](https://rapidapi.com/developer/billing/subscriptions-and-usage)). This API is free to sign up for and use
**`limit`** | `number` | _Optional_ | For busy airports, you may wish to limit the number of results visible
**`direction`** | `string` | _Optional_ | By default, both departure and arrival flights will be fetched, if you would like to only show flights in one direction, set this to wither `departure` or `arrival`
##### Example
```yaml
- type: flight-data
options:
airport: EGLC
apiKey: XXXXX
limit: 12
direction: all
```
---
## Dynamic Widgets

View File

@ -0,0 +1,197 @@
<template>
<div class="flight-wrapper">
<!-- Info -->
<p class="flight-intro">
Live {{ direction !== 'both' ? direction: 'flight' }} data from {{ airport }}
</p>
<!-- Departures -->
<div v-if="departures.length > 0" class="flight-group">
<h3 class="flight-type-subtitle" v-if="direction === 'both'">
Departures
</h3>
<div v-for="flight in departures" :key="flight.number" class="flight" v-tooltip="tip(flight)">
<p class="info flight-time">{{ flight.time | formatDate }}</p>
<p class="info flight-number">{{ flight.number }}</p>
<p class="info flight-airport">{{ flight.airport }}</p>
</div>
</div>
<!-- Arrivals -->
<div v-if="arrivals.length > 0" class="flight-group">
<h3 class="flight-type-subtitle" v-if="direction === 'both'">
Arrivals
</h3>
<div v-for="flight in arrivals" :key="flight.number" class="flight" v-tooltip="tip(flight)">
<p class="info flight-time">{{ flight.time | formatDate }}</p>
<p class="info flight-number">{{ flight.number }}</p>
<p class="info flight-airport">{{ flight.airport }}</p>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
import WidgetMixin from '@/mixins/WidgetMixin';
import { widgetApiEndpoints } from '@/utils/defaults';
export default {
mixins: [WidgetMixin],
components: {},
data() {
return {
departures: [],
arrivals: [],
};
},
mounted() {
this.fetchData();
},
filters: {
formatDate(date) {
const d = new Date(date);
if (Number.isNaN(d.getHours())) return '[UNKNOWN]';
return `${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`;
},
},
computed: {
/* The users desired airport, specified as a 4-digit ICAO-code */
airport() {
const usersChoice = this.options.airport;
if (!usersChoice) {
this.error('A valid airport must be specified');
return '';
}
const formattedAirport = usersChoice.toUpperCase().trim();
if (!(/[A-Z]{4}/).test(formattedAirport)) {
this.error('Incorrect airport format, must be a valid 4-digit ICAO-code');
return '';
}
return formattedAirport;
},
apiKey() {
const usersChoice = this.options.apiKey;
if (!usersChoice) {
this.error('An API key must be supplied');
return '';
}
return usersChoice;
},
/* The direction of flights: Arrival, Departure or Both */
direction() {
const usersChoice = this.options.direction;
if (!usersChoice || typeof usersChoice !== 'string') return 'both';
const options = ['arrival', 'departure', 'both'];
if (options.includes(usersChoice.toLowerCase())) return usersChoice;
return 'both';
},
limit() {
const usersChoice = this.options.limit;
if (usersChoice && !Number.isNaN(usersChoice)) return usersChoice;
return 8;
},
/* The starting date, right now, in ISO String format */
fromDate() {
const now = new Date();
return new Date(`${now.toString().split('GMT')[0]} UTC`).toISOString().split('.')[0];
},
/* The ending date, 12 hours from now, in ISO string format */
toDate() {
const now = new Date(new Date().setSeconds(0));
const tomorrow = new Date(new Date(now).setHours(now.getHours() + 12));
return new Date(`${tomorrow.toString().split('GMT')[0]} UTC`).toISOString().split('.')[0];
},
endpoint() {
return `${widgetApiEndpoints.flights}${this.airport}/${this.fromDate}/${this.toDate}`;
},
},
methods: {
/* Extends mixin, and updates data. Called by parent component */
update() {
this.startLoading();
this.fetchData();
},
/* Make GET request to CoinGecko API endpoint */
fetchData() {
const requestConfig = {
method: 'GET',
url: this.endpoint,
params: {
withCargo: 'true',
withPrivate: 'true',
withLocation: 'false',
},
headers: {
'x-rapidapi-host': 'aerodatabox.p.rapidapi.com',
'x-rapidapi-key': this.apiKey,
},
};
axios.request(requestConfig)
.then((response) => {
this.processData(response.data);
}).catch((error) => {
this.error('Unable to fetch flight data', error);
}).finally(() => {
this.finishLoading();
});
},
/* Assign data variables to the returned data */
processData(data) {
this.arrivals = this.makeFlightList(data.arrivals).slice(0, this.limit);
this.departures = this.makeFlightList(data.departures).slice(0, this.limit);
},
/* Gets the useful flight info out of departures or arrivals */
makeFlightList(flights) {
const results = [];
flights.forEach((flight) => {
results.push({
number: flight.number,
airline: flight.airline.name,
aircraft: flight.aircraft.model,
airport: flight.movement.airport.name,
time: flight.movement.actualTimeUtc,
});
});
return results;
},
tip(flight) {
const content = `${flight.aircraft} | ${flight.airline}`;
return {
content, trigger: 'hover focus', delay: 250, classes: 'in-modal-tt',
};
},
},
};
</script>
<style scoped lang="scss">
.flight-wrapper {
p.flight-intro {
margin: 0 0 0.5rem 0;
font-size: 1rem;
color: var(--widget-text-color);
opacity: var(--dimming-factor);
}
h3.flight-type-subtitle {
margin: 0.25rem 0;
font-size: 1.2rem;
color: var(--widget-text-color);
}
.flight-group {
.flight {
display: flex;
flex-direction: row;
justify-content: space-between;
padding: 0.25rem 0;
p.info {
margin: 0;
min-width: 33%;
color: var(--widget-text-color);
}
&:not(:last-child) {
border-bottom: 1px dashed var(--widget-text-color);
}
}
}
}
</style>

View File

@ -88,6 +88,13 @@
@error="handleError"
:ref="widgetRef"
/>
<Flights
v-else-if="widgetType === 'flight-data'"
:options="widgetOptions"
@loading="setLoaderState"
@error="handleError"
:ref="widgetRef"
/>
<IframeWidget
v-else-if="widgetType === 'iframe'"
:options="widgetOptions"
@ -121,6 +128,7 @@ import ExchangeRates from '@/components/Widgets/ExchangeRates.vue';
import StockPriceChart from '@/components/Widgets/StockPriceChart.vue';
import Jokes from '@/components/Widgets/Jokes.vue';
import IframeWidget from '@/components/Widgets/IframeWidget.vue';
import Flights from '@/components/Widgets/Flights.vue';
export default {
name: 'Widget',
@ -140,6 +148,7 @@ export default {
StockPriceChart,
Jokes,
IframeWidget,
Flights,
},
props: {
widget: Object,

View File

@ -214,6 +214,7 @@ module.exports = {
exchangeRates: 'https://v6.exchangerate-api.com/v6/',
stockPriceChart: 'https://www.alphavantage.co/query',
jokes: 'https://v2.jokeapi.dev/joke/',
flights: 'https://aerodatabox.p.rapidapi.com/flights/airports/icao/',
},
/* URLs for web search engines */
searchEngineUrls: {