npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

openmeteo

v1.1.4

Published

Open-Meteo Weather API

Downloads

26,207

Readme

Open-Meteo API Typescript SDK

npm package Build Status Downloads Issues Commitizen Friendly Semantic Release

This is a TypeScript/Javascript API client designed for retrieving weather information from the Open-Meteo Weather API in Typescript / Javascript.

Unlike conventional JSON APIs, this API client employs FlatBuffers for data transfer. This is a more efficient method, particularly for handling extended time-series data. You can locate the schema definition files on GitHub open-meteo/sdk.

Features:

  • Easily access weather data
  • Retrieve weather data for multiple locations with a single request
  • Automatic retry mechanism for handling errors
  • Enhanced bandwidth efficiency and speedy parsing using FlatBuffers and Zero Copy technology
  • Type annotations for enhanced code clarity

Install

npm install openmeteo

Usage

Note: The Open-Meteo API documentation generates the required Typescript code automatically.

import { fetchWeatherApi } from 'openmeteo';

const params = {
    latitude: [52.54],
    longitude: [13.41],
    current: 'temperature_2m,weather_code,wind_speed_10m,wind_direction_10m',
    hourly: 'temperature_2m,precipitation',
    daily: 'weather_code,temperature_2m_max,temperature_2m_min'
};
const url = 'https://api.open-meteo.com/v1/forecast';
const responses = await fetchWeatherApi(url, params);

// Helper function to form time ranges
const range = (start: number, stop: number, step: number) =>
	Array.from({ length: (stop - start) / step }, (_, i) => start + i * step);

// Process first location. Add a for-loop for multiple locations or weather models
const response = responses[0];

// Attributes for timezone and location
const utcOffsetSeconds = response.utcOffsetSeconds();
const timezone = response.timezone();
const timezoneAbbreviation = response.timezoneAbbreviation();
const latitude = response.latitude();
const longitude = response.longitude();

const current = response.current()!;
const hourly = response.hourly()!;
const daily = response.daily()!;

// Note: The order of weather variables in the URL query and the indices below need to match!
const weatherData = {
    current: {
        time: new Date((Number(current.time()) + utcOffsetSeconds) * 1000),
        temperature: current.variables(0)!.value(), // Current is only 1 value, therefore `.value()`
        weatherCode: current.variables(1)!.value(),
        windSpeed: current.variables(2)!.value(),
        windDirection: current.variables(3)!.value()
    },
    hourly: {
        time: range(Number(hourly.time()), Number(hourly.timeEnd()), hourly.interval()).map(
            (t) => new Date((t + utcOffsetSeconds) * 1000)
        ),
        temperature: hourly.variables(0)!.valuesArray()!, // `.valuesArray()` get an array of floats
        precipitation: hourly.variables(1)!.valuesArray()!,
    },
    daily: {
        time: range(Number(daily.time()), Number(daily.timeEnd()), daily.interval()).map(
            (t) => new Date((t + utcOffsetSeconds) * 1000)
        ),
        weatherCode: daily.variables(0)!.valuesArray()!,
        temperatureMax: daily.variables(1)!.valuesArray()!,
        temperatureMin: daily.variables(2)!.valuesArray()!,
    }
};

// `weatherData` now contains a simple structure with arrays for datetime and weather data
for (let i = 0; i < weatherData.daily.time.length; i++) {
  console.log(
    weatherData.daily.time[i].toISOString(), 
    weatherData.daily.weatherCode[i], 
    weatherData.daily.temperatureMax[i], 
    weatherData.daily.temperatureMin[i]
  );
}

Parameter

This package only exposes one function to fetch weather data and decode the FlatBuffer messages.

/**
 * Retrieve data from the Open-Meteo weather API
 * 
 * @param {string} url Server and endpoint. E.g. "https://api.open-meteo.com/v1/forecast"
 * @param {any} params URL parameter as an object
 * @param {number} [retries=3] Number of retries in case of an server error
 * @param {number} [backoffFactor=0.2] Exponential backoff factor to increase wait time after each retry
 * @param {number} [backoffMax=2] Maximum wait time between retries
 * @returns {Promise<WeatherApiResponse[]>}
 */
async function fetchWeatherApi(
  url: string,
  params: any,
  retries = 3,
  backoffFactor = 0.2,
  backoffMax = 2
): Promise<WeatherApiResponse[]> {
}