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

Feature: Netlify server less function to fetch Weather Data #114

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Local Netlify folder
.netlify
.vscode
node_modules/
.env
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,35 @@
- Click on the **Compare & pull request** button.
- Submit the pull request.

## 🚀 Local Setup Guide

1. **Add ENVIRONMENT variables**
```bash
OPENWEATHERMAP_TOKEN=your_open_weather_api_key
WEATHER_API_BASE_URL=https://api.openweathermap.org/data/2.5/weather
WEATHER_DATA_UNIT=metric
```
Keep your `.env` file inside `netlify/functions` directory.
2. **Install required packages**
Run:
```bash
npm i
```
3. **Intall Netlify CLI locally**
This site is hosted on Netlify. Netlify CLI is needed to run it locally.
```bash
npm install netlify-cli --global
```
Check version
```bash
ntl --version
```
4. **Run project in local**
```bash
netlify dev
```


It's that easy! We are eagerly waiting for your pull request. 😊

## 📝 How to Get Concluded
Expand Down
15 changes: 9 additions & 6 deletions js/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,22 +38,25 @@ window.getWeather = function () {
// Check if the input is not empty
if (input) {
// Create a URL for the weather API with the input as a query parameter
const token = OPENWEATHERMAP_TOKEN;
var url = "https://api.openweathermap.org/data/2.5/weather?q=" + input + "&units=metric&appid=" + token;

// Fetch the data from the URL using the fetch API
fetch(url)
// Fetch the data from netlify function using the fetch API
fetch(`/.netlify/functions/getWeatherData?city=${input}`)
.then(function (response) {
// Check if the response is ok
if (response.ok) {
// Convert the response to JSON format
return response.json();
} else {
// Throw an error if the response is not ok
throw new Error("Something went wrong");
throw new Error(`Invalid response code from open weather API: ${response.status}`);
}
})
.then(function (data) {
.then(function (responseData) {
let data = responseData["data"]
if(!data){
console.log(responseData["error"])
throw new Error(responseData["error"])
}
// Extract the relevant data from the JSON object
var city = data.name; // The city name
var country = data.sys.country; // The country code
Expand Down
39 changes: 39 additions & 0 deletions netlify/functions/getWeatherData.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import dotenv from "dotenv";
dotenv.config({ path: "./netlify/functions/.env" });

export const handler = async (event) => {
let status = 500;
try {
let { city } = event.queryStringParameters;
const baseUrl = process.env.WEATHER_API_BASE_URL;
const appKey = process.env.OPENWEATHERMAP_TOKEN;
const units = process.env.WEATHER_DATA_UNIT;
const url = `${baseUrl}?q=${city}&appid=${appKey}&units=${units}`;
let response = await fetch(url);
if (response.ok) {
status = response.status;
let data = await response.json();
return {
statusCode: status,
body: JSON.stringify({
error: null,
data: data,
}),
};
} else {
status = response.status;
throw new Error(
`Invalid response code from open weather API: ${response.status}`
);
}
} catch (error) {
console.log(error.message);
return {
statusCode: status,
body: JSON.stringify({
error: error.message,
data: null,
}),
};
}
};
24 changes: 24 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"type": "module",
"dependencies": {
"dotenv": "^16.4.5"
}
}