Skip to content

Commit

Permalink
Added weather fetching API
Browse files Browse the repository at this point in the history
  • Loading branch information
jamie6king committed Nov 14, 2024
1 parent edd4823 commit f567797
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 3 deletions.
35 changes: 35 additions & 0 deletions server/fetcher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import dotenv from "dotenv";
dotenv.config();

export class WeatherFetcher {

consturctor() {
this._apiKey = process.env.API_KEY;
};

// fetch lang+long co-ords for API
async _fetchCoords(city) {
const url = `http://api.openweathermap.org/geo/1.0/direct?q=${city}&limit=3&appid=${process.env.API_KEY}`; // specifying this._apiKey doesn't work???

const result = await fetch(url);
return await result.json();
};

// fetch list of potential cities
async fetchCities(string) {
const coords = await this._fetchCoords(string);
return coords.map((city) => { return {
name: city.name,
countryCode: city.country,
lat: city.lat,
lon: city.lon
};});
};

async fetchWeather(lat, lon) {
const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${process.env.API_KEY}`;

const result = await fetch(url);
return await result.json();
};
};
32 changes: 32 additions & 0 deletions tests/jest/fetcher.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { WeatherFetcher } from "../../server/fetcher.js";

describe("weather fetching", () => {

it("fetches city co-ords", async () => {
const fetcher = new WeatherFetcher();
const coords = await fetcher._fetchCoords("london");

expect(coords[0].name).toBe("London");
});

it("fetches list of cities", async () => {
const fetcher = new WeatherFetcher();
const list = await fetcher.fetchCities("london");

expect(list[0].name).toBe("London");
expect(list[1].name).toBe("City of London");
expect(list[2].countryCode).toBe("CA");
});

it("fetches the weather data for a city", async () => {
const fetcher = new WeatherFetcher();
const coords = await fetcher._fetchCoords("london");

const lat = coords[0].lat;
const lon = coords[0].lon;

const weather = await fetcher.fetchWeather(lat, lon);

expect(weather.name).toBe("London");
});
});
6 changes: 3 additions & 3 deletions tests/playwright/dummy.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { test, expect } from "@playwright/test";

test("loads", async ({ page }) => {
await page.goto("./")
await expect(page).toHaveTitle("SkyCast")
})
await page.goto("./");
await expect(page).toHaveTitle("SkyCast");
});

0 comments on commit f567797

Please sign in to comment.