Giter Site home page Giter Site logo

worldturtlemedia / darksky-api Goto Github PK

View Code? Open in Web Editor NEW
8.0 2.0 3.0 3.24 MB

API Wrapper for DarkSky.net written in TypeScript.

Home Page: https://worldturtlemedia.github.io/darksky-api/

License: MIT License

TypeScript 100.00%
darksky darksky-api typescript node api-wrapper

darksky-api's Introduction

DarkSky API Wrapper

Archived

This library has been archived because of DarkSky shutting down.

If you need a service/API that is similar to DarkSky, I would recommend OpenWeatherMap onecall. You can find a smiliar library for that API here.

=====================================

A wrapper for DarkSky API written in TypeScript.

NOTE

It looks like DarkSky will be shutting down their API in 2021, so this library will not receive anymore feature updates, only security and bugfixes. See #385 for more.


Usable in node and the browser. If used in a TypeScript project, you will get types, and auto-complete for all of the api responses. You will no longer need to tab back and fourth to the API documentation. Will work in Node or the browser!

This library makes interacting with the DarkSky API a little bit more friendly. It offers promises, request customization, and best of all response types.

If there are any features you would like, please feel free to open up an issue.

Note

I did my best to correctly add types for all of the supported endpoints. However if you notice an incorrect payload type, or some missing properties, please open up an issue, or submit a pull request.

Warning

DarkSky explicitly forbids CORS so using darkskyapi-ts in the browser will not work, and you should instead setup a proxy server and run it on the background.

To prevent API key abuse, you should set up a proxy server to make calls to our API behind the scenes. Then you can provide forecasts to your clients without exposing your API key.

Installation

Add using yarn or npm

yarn add darkskyapi-ts

Usage

Create an account on DarkSky.net, then get your API token.

There are a couple ways to use this library.

TimeMachine request

Any request can be made into a TimeMachine request by passing { time: 'some-timestamp' } into any function that accepts an optional params object.

The time property an be any of the following:

  • Date object.
  • A valid formatted date-string.
  • UNIX timestamp.

Either be a UNIX timestamp or a string formatted as follows:

// UNIX timestamp
{
  time: 1558575452
}

// Date string
// [YYYY]-[MM]-[DD]T[HH]:[MM]:[SS][timezone].
{
  time: '2019-01-01T00:00:00+0400'
}

The library will try it's best to parse the Date string you pass in, so you don't need to supply it in the above format. But for safety its probably best.

Timezone should either be omitted (to refer to local time for the location being requested), Z (referring to GMT time), or +[HH][mm] or -[HH][mm] for an offset from GMT in hours and minutes.

1. DarkSky class

Get instance of the factory. See demo/demo_class.ts`

Use any of the DarkSky helper functions (see below).

// Optional Default options
const options: DarkSkyOptions = {
  // Optional
  // Anything set here can be overriden when making the request

  units: Units.SI,
  lang: Language.FRENCH
}

// Create the api wrapper class
const darksky = new DarkSky(KEY, options)

// Use the wrapper

/**
 * Will get the weekly forecast using a helper function, it excludes all of the datablocks except
 * for the `daily` one.  If you need more than that you can use `DarkSky.forecast` and pass in
 * an Exclude array.
 */
async function getWeeklyForecast(lat: number, lng: number): Promise<WeekForecast> {
  try {
    // You can pass options here to override the options set above
    const result: WeekForecast = await darksky.week(lat, lng, { lang: Language.ENGLISH })
    console.log(`Got forecast for ${result.latitude}-${result.longitude}`)
    return result
  } catch (error) {
    // If DarkSky API doesn't return a 'daily' data-block, then this function will throw
    console.log('Unable to get the weekly forecast for the chosen location')
  }
}

;(async () => {
  const forecast = await getWeeklyForecast(42, 24)

  console.log(`Forecast for tomorrow: ${forecast.daily.data[1].temperatureMax}`)
})()

2. Chaining

You can build a request by using method chaining and a builder pattern.

// Using helper function
import { createRequestChain } from 'darksky-api'

createRequestChain('api-key', 42, 24)
  .extendHourly()
  .onlyHourly()
  .excludeFlags()
  .excludeAlerts()
  .execute()
  .then(console.log)
  .catch(console.log)

// Using the DarkSky class
new DarkSky('api-key')
  .chain(42, 24)
  .time('May 05 2019') // Library will try it's best to parse this date string
  .units(Units.UK)
  .execute()
  .then(console.log)
  .catch(console.log)

3. Manual DarkSky client

This library also exports a minimal DarkSky wrapper, where you can manually create the requests.

import { createClient } from 'darksky-api'

const targetDate = new Date(1558000000 * 1000)

createClient('api-key')
  .timeMachine({ latitude: 42, longitude: 24, time: targetDate }, { units: Units.CA })
  .then(console.log)
  .catch(console.log)

DarkSky class helper methods

Optional settings when creating a new wrapper:

export interface DarkSkyOptions {
  /**
   * Return weather conditions in the requested units.
   *
   * @default Units.AUTO
   */
  units?: Units

  /**
   * Return summary properties in the desired language.
   *
   * @default Language.ENGLISH
   */
  lang?: Language

  /**
   * When true, return hour-by-hour data for the next 168 hours, instead of the next 48.
   *
   * @default false
   */
  extendHourly?: boolean

  /**
   * Exclude some number of data blocks from the API response.
   */
  exclude?: Exclude[]

  /**
   * Optional config to change the way axios makes the request.
   */
  requestConfig?: AxiosRequestConfig
}

All helper methods require the location latitude: number, longitude: number, and can take an optional settings object.

If you need the forecast for a specific date and time, you can use DarkSky's TimeMachine functionality by passing a time property to each helper function, example:

new DarkSky('api-key').week(42, 24, { time: 'May 5 2018' })
Name Optional Returns
chain() RequestParams DarkSkyRequestChain
forecast() RequestParams Forecast
timeMachine() RequestParams Forecast
current() RequestParams CurrentForecast
week() RequestParams WeekForecast
day() RequestParams DayForecast
hour() RequestParams HourForecast

chain() is a special function that allows you to create a DarkSkyRequestChain to build your own request, see the example above.

Demo

Demos are available in the demo/ folder. You will NEED a DarkSky API key for the demos to work. Then you can either set it in your env, or pass it as an CLI argument. See the example below.

Note: I recommend VSCode for viewing and editing the examples. It will give you great intellisense about the library.

Follow the steps below:

# Get a API token from DarkSky.net

# Either set it in your env
export DARKSKY_KEY=your-token

# or pass it as a cli argument
# npx ts-node --project ../tsconfig.base.json demo_[demo name].ts --key your-key

# Build the library
yarn && yarn build

# Change into demo folder and install dependencies
cd demo
yarn

# Typescript example:
npx ts-node --project ../tsconfig.base.json demo_[demo name].ts

# To view Browser example, first build project
yarn build

# Then open `index.html` in your browser

Contributing

See CONTRIBUTING.

License

MIT License

Copyright (c) 2019 WorldTurtleMedia

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

darksky-api's People

Contributors

chrisdrackett avatar dependabot[bot] avatar jordond avatar renovate-bot avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

darksky-api's Issues

Thanks!

Good work on typing the Darksky API. I recently added this as a dependancy to our apps for the definitions to type-check the response from our internal proxy of the DS data. I am going to ask my contact at DS to look into your repo and maybe feature it or possibly the definitions on their site. It saved me a bunch of time and now I know that the data will be correct. Thanks! Expect a bunch of installs from your NPM repo in the next month or so, when this sprint is released to production.

Feature: Add flag to format unix timestamps into Javascript Date timestamps

Right now the response that comes back from DarkSky will not create the correct date in javascript. You have to do this:

const { dt } = forecast.current
const data = new Date(dt * 1000) 

It would be nice to have an optional flag that would convert the response automatically.

Something like:

new DarkSky('token', { formatTimestamp: true })

issues with date format

I'm sending the following date into a timeMachine request:

2019-09-20T21:04:59.967Z

and the following is being sent (and rejected) by DarkSky:

2019-09-20156901349996714:04:59-0700

looking into the code now, but wanted to get the issue reported!

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.