Article: Fetching data

In this plugin example, we'll make a simple utility where the user can load the current real world METAR from a web API. The user will be able to program a keyboard shortcut or button that when pressed will prompt them for the airfield's ICAO identifier. When an invalid identifier is supplied, the current METAR will be loaded and shown. When an invalid ICAO identifier is supplied, feedback will be shown to the user.

Note: While this code uses some GUI elements, they are all available in the free version of JetScript. For fancier UIs, and the use of widgets / layouts, a commercial license is neeeded. (Link: more about commercial licenses)

Set up a new plugin

To get started, set up a new plugin as detailed in the getting started page.

console.log("Hello world!")

Set up a command

The user will use a command to start the process. To do that, we'll need to set up a command, and a function to handle when the command is activated.

let command = simulator.createCommand("example/metar/request", "Request METAR for an airfield")

command.addEventListener("end", (event) => { console.log("We'll prompt the user here for the airport identifier")})

Command documentation

Prompt for the airport identifier

Javascript provides some handy basic UI functions to get basic user input without too much trouble. While these aren't the prettiest, the alert(), confirm(), and prompt() dialogs are really easy to get started with.

Let's prompt the user for an ICAO identifier, and check to make sure it looks valid. For this check, we'll simply verify that it's a 4-digit alpha-numeric string, using regular expressions.

let command = simulator.createCommand("example/metar/request", "Request METAR for an airfield");

function prompt_for_icao() {
    let user_entered_icao = prompt("Enter an ICAO identifier (4 letters):");

    // Loop until we get something valid
    while(true) {
        // If the user pressed Cancel, we're done.
        if user_entered_icao == undefined {
            console.info("The user changed their mind.")
            return;
        }

        const icao_regex = /^[A-Za-z]{4}$/;

        if(bool(icao_regex.match(user_entered_icao))) {
            // If it's valid, then let's break out of the loop and go fetch it!
            break;
        } else {
            // If not valid, try again.
            user_entered_icao = prompt(`${user_entered_icao} is not a 4-character identifier.\n\nEnter a 4-character ICAO identifier:`);
        }
    }

    console.info(`The user wants the METAR for ${user_entered_icao}!`);

    // Next:
    // fetch_metar(user_entered_icao)
}

command.addEventListener("end", (event) => prompt_for_icao());

prompt() documentation Javascript regex literals `Regex.match()`` documentation (MDN)

Fetch and display the result

Finally, let's do the actual work! We now have an ICAO identifier of an airfield that we should fetch the METAR for. Javascript's fetch() function can be used to make HTTP and HTTPS requests. First, we'll construct the URL that we're going to use to fetch data, and then we can call fetch() with a URL, and will get back a promise to the result.

TODO IMAGE: of METAR result

// Docs for this API: https://beta.aviationweather.gov/data/example/
let url = `https://beta.aviationweather.gov/cgi-bin/data/metar.php?ids={user_entered_icao}`;
fetch(url).then((response) => {
    if(resonse.success) {
        alert(response.text);
    } else {
        alert(`Failed to fetch METAR for ${user_entered_icao}: ${response.code}`);
    }
})

fetch() documentation

Putting it all together

Here's the complete code for this example:

let command = simulator.createCommand("example/metar/request", "Request METAR for an airfield");

function prompt_for_icao() {
    prompt("Enter an ICAO identifier (4 letters):").then((user_entered_icao) {
        if(user_entered_icao != null) {
            // The user pressed OK, and likely entered something.
            validate_icao(user_entered_icao);
        } else {
            // The user pressed cancel
            console.info("The user changed their mind.");
        }
    });
}

function validate_icao(icao_identifier) {

    const icao_regex = /^[A-Za-z]{4}$/;

    if(Boolean(user_entered_icao.match(icao_regex))) {
        // If it's valid, then let's go fetch it!
        fetch_icao(icao_identifier);
    } else {
        // If not valid, provide feedback
        alert(`${user_entered_icao} is not a 4-character identifier.\n\nEnter a 4-character ICAO identifier:`);
    }
}

function fetch_icao(icao_identifier) {
    console.info(`The user wants the METAR for ${user_entered_icao}!`);

    let url = `https://beta.aviationweather.gov/cgi-bin/data/metar.php?ids=${user_entered_icao}`;
    fetch(url).then((response) => {
        if(resonse.success) {
            console.trace("Received METAR from server");
            alert(response.text);
        } else {
            console.error(`Error retrieving METAR. HTTP code ${response.code}`);
            alert(`Failed to fetch METAR for ${user_entered_icao}: ${response.code}`);
        }
    })
}

command.addEventListener("end", (event) => prompt_for_icao());