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

merge #2

Open
wants to merge 9 commits into
base: master
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
138 changes: 94 additions & 44 deletions dark-sky-api.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,40 @@
'use strict'
const req = require('request')
const moment = require('moment')
const queryString = require('query-string')

const truthyOrZero = value => !!value || parseFloat(value) === 0
const req = require("request")
const moment = require("moment")
const queryString = require("query-string")

class DarkSky {
constructor(apiKey) {
this.apiKey = apiKey
this.long = null
this.lat = null
this.t = null
this.timeVal = null
this.query = {}
this.timeout = 20000
this.timeoutVal = 20000
this.gzip = false
}

static truthyOrZero(value) {
return !!value || parseFloat(value) === 0
}

compression(val) {
if (DarkSky.truthyOrZero(val)) {
this.gzip = val
}
return this
}

longitude(long) {
!truthyOrZero(long) ? null : (this.long = long)
if (DarkSky.truthyOrZero(long)) {
this.long = long
}
return this
}

latitude(lat) {
!truthyOrZero(lat) ? null : (this.lat = lat)
if (DarkSky.truthyOrZero(lat)) {
this.lat = lat
}
return this
}

Expand All @@ -32,35 +45,57 @@ class DarkSky {
}

time(time) {
!truthyOrZero(time)
? null
: (this.t = moment(new Date(time)).format('YYYY-MM-DDTHH:mm:ss'))
if (DarkSky.truthyOrZero(time)) {
this.timeVal = moment(new Date(time)).format("YYYY-MM-DDTHH:mm:ss")
} else {
this.timeVal = null
}
return this
}

units(unit) {
!unit ? null : (this.query.units = unit)
if (unit) {
this.query.units = unit
} else {
this.query.units = null
}
return this
}

language(lang) {
!lang ? null : (this.query.lang = lang)
if (lang) {
this.query.lang = lang
} else {
this.query.lang = null
}
return this
}

exclude(blocks) {
blocks = Array.isArray(blocks) ? blocks.join(',') : blocks
!blocks ? null : (this.query.exclude = blocks)
blocks = Array.isArray(blocks) ? blocks.join(",") : blocks
if (blocks) {
this.query.exclude = blocks
} else {
this.query.exclude = null
}
return this
}

extendHourly(param) {
!param ? null : (this.query.extend = 'hourly')
if (param) {
this.query.extend = "hourly"
} else {
this.query.extend = null
}
return this
}

timeout(miliseconds) {
!miliseconds ? null : (this.timeout = miliseconds)

timeout(milliseconds) {
if (milliseconds) {
this.timeoutVal = milliseconds
} else {
this.timeoutVal = null
}
return this
}

Expand All @@ -70,10 +105,11 @@ class DarkSky {
Object.getPrototypeOf(this)
).filter(
method =>
method !== 'constructor' &&
method !== 'get' &&
method !== 'options' &&
method.indexOf('_') === -1
method !== "constructor" &&
method !== "get" &&
method !== "options" &&
method !== "truthyOrZero" &&
method.indexOf("_") === -1
)
// get keys of options object passed
return Object.keys(options).reduce((acc, val) => {
Expand All @@ -86,32 +122,46 @@ class DarkSky {
}

_generateReqUrl() {
this.url = `https://api.darksky.net/forecast/${this.apiKey}/${this
.lat},${this.long}`
this.t ? (this.url += `,${this.t}`) : this.url
this.query
? (this.url += `?${queryString.stringify(this.query)}`)
: this.url
this.url = `https://api.darksky.net/forecast/${this.apiKey}/${this.lat},${
this.long
}`
if (this.timeVal) {
this.url += `,${this.timeVal}`
}
if (this.query) {
this.url += `?${queryString.stringify(this.query)}`
}
return true
}

get() {
return new Promise((resolve, reject) => {
if (!truthyOrZero(this.lat) || !truthyOrZero(this.long))
reject('Request not sent. ERROR: Longitute or Latitude is missing.')
if (!DarkSky.truthyOrZero(this.lat) || !DarkSky.truthyOrZero(this.long)) {
reject("Request not sent. ERROR: Longitute or Latitude is missing.")
}

this._generateReqUrl()

req({ url: this.url, json: true, timeout: this.timeout }, (err, res, body) => {
if (err) {
reject(`Forecast cannot be retrieved. ERROR: ${err}`)
return
}
res.statusCode !== 200
? reject(
`Forecast cannot be retrieved. Response: ${res.statusCode} ${res.statusMessage}`
req(
{ url: this.url, json: true, timeout: this.timeoutVal, gzip: this.gzip },
(err, res, body) => {
if (err) {
reject(`Forecast cannot be retrieved. ERROR: ${err}`)
return
}

if (res.statusCode !== 200) {
reject(
`Forecast cannot be retrieved. Response: ${res.statusCode} ${
res.statusMessage
}`
)
: null
resolve(body)
})
return
}

resolve(body)
}
)
})
}
}
Expand Down
33 changes: 23 additions & 10 deletions dark-sky-api.test.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
const DarkSky = require('./dark-sky-api')
const DarkSky = require("./dark-sky-api")
let forecast

test('return instance of darksky class', async () => {
test("return instance of darksky class", async () => {
const darksky = new DarkSky(process.env.DARK_SKY)
expect(darksky).toBeInstanceOf(DarkSky)
})

test('return the forecast for Toronto on 1991-06-02 using options method', async () => {
test("return the forecast for Toronto on 1991-06-02 using options method", async () => {
const darksky = new DarkSky(process.env.DARK_SKY)
const result = await darksky
.options({
longitude: -79.411079,
latitude: 43.761539,
time: '1991-06-02',
units: 'ca',
language: 'en',
exclude: ['minutely', 'daily'],
time: "1991-06-02",
units: "ca",
language: "en",
exclude: ["minutely", "daily"],
extendHourly: true
})
.get()
Expand All @@ -24,11 +24,11 @@ test('return the forecast for Toronto on 1991-06-02 using options method', async
expect(result.minutely).toBeFalsy()
expect(result.daily).toBeFalsy()
expect(result.hourly).toBeTruthy()
expect(result.currently.time).toBe(675820800)
expect(result.timezone).toBe('America/Toronto')
expect(result.currently.time).toBe(675817200)
expect(result.timezone).toBe("America/Toronto")
})

test('return the current forecast for Toronto using coordinates method and method chaining', async () => {
test("return the current forecast for Toronto using coordinates method and method chaining", async () => {
const darksky = new DarkSky(process.env.DARK_SKY)
const result = await darksky
.coordinates({
Expand All @@ -39,3 +39,16 @@ test('return the current forecast for Toronto using coordinates method and metho
expect(result.latitude).toBe(43.761539)
expect(result.longitude).toBe(-79.411079)
})

test("return the current forecast for Toronto using compression", async () => {
const darksky = new DarkSky(process.env.DARK_SKY)
const result = await darksky
.coordinates({
lat: 43.761539,
lng: -79.411079
})
.compression(true)
.get()
expect(result.latitude).toBe(43.761539)
expect(result.longitude).toBe(-79.411079)
})
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
{
"name": "dark-sky",
"version": "1.1.2",
"description": "A dead simple Dark Sky API wrapper for Nodejs using method chaining and promises.",
"version": "1.1.5",
"description":
"A dead simple Dark Sky API wrapper for Nodejs using method chaining and promises.",
"main": "dark-sky-api.js",
"scripts": {
"test": "./node_modules/.bin/jest"
Expand Down
Loading