forked from deanbot/angular-dark-sky
-
Notifications
You must be signed in to change notification settings - Fork 0
/
angular-dark-sky.js
407 lines (377 loc) · 12.8 KB
/
angular-dark-sky.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/**
* angular-dark-sky
*
* A simple & configurable provider for the Dark Sky API including icon directive using weather-icons
*
* @link https://github.com/deanbot/angular-dark-sky
* @see {@link https://darksky.net/dev/}
* @see {@link https://darksky.net/dev/docs/|Docs}
* @see {@link http://erikflowers.github.io/weather-icons|weather-icons}
* @author Dean Verleger <[email protected]>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
(function () {
'use strict';
angular.module('dark-sky', [])
.provider('darkSky', darkSkyProvider)
.directive('darkSkyIcon', ['darkSky', darkSkyIcon]);
/**
* Dark Sky weather data provider
*/
function darkSkyProvider() {
var apiKey,
config = {
baseUri: 'https://api.darksky.net/forecast/',
baseExclude: '&exclude=',
acceptedUnits: ['auto', 'ca', 'uk2', 'us', 'si'],
acceptedLanguage: [
'ar', 'az', 'be', 'bs', 'cs', 'de', 'el', 'en', 'es', 'fr', 'hr', 'hu', 'id', 'it', 'is', 'kw', 'nb', 'nl', 'pl', 'pt', 'ru', 'sk', 'sr', 'sv', 'tet', 'tr', 'uk', 'x-pig-latin', 'zh', 'zh-tw'
]
},
units = 'us', // default unit
language = 'en'; // default language
/**
* Set API key for request
* @param {String} value - your Dark Sky API key
*/
this.setApiKey = function (value) {
apiKey = value;
return this;
};
/**
* Set unit type for response formatting
* @param {String} value - unit token
*/
this.setUnits = function (value) {
if (config.acceptedUnits.indexOf(value) === -1) {
console.warn(value + ' not an accepted API unit.');
}
units = value;
return this;
};
/**
* Set language for response summaries
* @param {String} value - language token
*/
this.setLanguage = function (value) {
if (config.acceptedLanguage.indexOf(value) === -1) {
console.warn(value + ' not an accepted API language.');
}
language = value;
return this;
};
/**
* Service definition
*/
this.$get = ['$http', '$q', function ($http, $q) {
var service = {
getCurrent: getCurrent,
getForecast: getForecastDaily,
getDailyForecast: getForecastDaily,
getHourlyForecast: getForecastHourly,
getMinutelyForecast: getForecastMinutely,
getAlerts: getAlerts,
getFlags: getFlags,
getUnits: getUnits
};
if (!apiKey) {
console.warn('No Dark Sky API key set.');
}
return service;
/** Public Methods */
/**
* Get current weather data
* @param {number} latitude position
* @param {number} longitude position
* @param {object} [options] - additional query options
* ... {unix timestamp} options.time - send timestamp for timemachine requests
* @returns {promise} - resolves with current weather data object
*/
function getCurrent(latitude, longitude, options) {
return api(latitude, longitude, options).current();
}
/**
* Get daily weather data
* @param {number} latitude positition
* @param {number} longitude positition
* @param {object} [options] - additional query options
* ... {unix timestamp} options.time - send timestamp for timemachine requests
* ... {boolean} options.extend - pass true for extended forecast
* @returns {promise} - resolves with daily weather data object
*/
function getForecastDaily(latitude, longitude, options) {
return api(latitude, longitude, options).daily();
}
/**
* Get hourly weather data
* @param {number} latitude positition
* @param {number} longitude positition
* @param {object} [options] - additional query options
* ... {unix timestamp} options.time - send timestamp for timemachine requests
* ... {boolean} options.extend - pass true for extended forecast
* @returns {promise} - resolves with hourly weather data object
*/
function getForecastHourly(latitude, longitude, options) {
return api(latitude, longitude, options).hourly();
}
/**
* Get minutely weather data
* @param {number} latitude positition
* @param {number} longitude positition
* @param {object} [options] - additional query options
* ... {unix timestamp} options.time - send timestamp for timemachine requests
* ... {boolean} options.extend - pass true for extended forecast
* @returns {promise} - resolves with minutely weather data object
*/
function getForecastMinutely(latitude, longitude, options) {
return api(latitude, longitude, options).minutely();
}
/**
* Get alerts weather data
* @param {number} latitude positition
* @param {number} longitude positition
* @param {object} [options] - additional query options
* ... {unix timestamp} options.time - send timestamp for timemachine requests
* ... {boolean} options.extend - pass true for extended forecast
* @returns {promise} - resolves with alerts weather data object
*/
function getAlerts(latitude, longitude, options) {
return api(latitude, longitude, options).alerts();
}
/**
* Get flags weather data
* @param {number} latitude positition
* @param {number} longitude positition
* @param {object} [options] - additional query options
* ... {unix timestamp} options.time - send timestamp for timemachine requests
* ... {boolean} options.extend - pass true for extended forecast
* @returns {promise} - resolves with flags weather data object
*/
function getFlags(latitude, longitude, options) {
return api(latitude, longitude, options).flags();
}
/**
* Get units object showing units returned based on configured language/units
* @returns {object} units
*/
function getUnits() {
var unitsObject,
// per API defualt assume 'us' if omitted
unitId = 'us';
// determine unit id
if (units) {
if (units === 'auto') {
console.warn('Can\'t guess units. Defaulting to Imperial');
unitId = 'us';
} else {
unitId = units;
}
}
// get units object by id
switch (unitId) {
case 'ca':
unitsObject = getCaUnits();
break;
case 'uk2':
unitsObject = getUk2Units();
break;
case 'us':
unitsObject = getUsUnits();
break;
case 'si':
unitsObject = getSiUnits();
break;
}
return unitsObject;
}
/** Private Methods */
/**
* Expose API methods with latitude and longitude mapping
* @param {number} latitude
* @param {number} longitude
* @param {object} options
* @returns {oObject} - object with API method properties
*/
function api(latitude, longitude, options) {
var time;
// check for time option
if (options && options.time) {
time = options.time;
}
return {
current: function () {
var query = excludeString('currently') + optionsString(options);
return fetch(latitude, longitude, query, time);
},
daily: function () {
var query = excludeString('daily') + optionsString(options);
return fetch(latitude, longitude, query, time);
},
hourly: function () {
var query = excludeString('hourly') + optionsString(options);
return fetch(latitude, longitude, query, time);
},
minutely: function () {
var query = excludeString('minutely') + optionsString(options);
return fetch(latitude, longitude, query, time);
},
alerts: function () {
var query = excludeString('alerts') + optionsString(options);
return fetch(latitude, longitude, query, time);
},
flags: function () {
var query = excludeString('flags') + optionsString(options);
return fetch(latitude, longitude, query, time);
}
};
}
/**
* Get exclude items by excluding all items except what is passed in
* @param {string} toRetrieve - single block to include in results
* @returns {string} - exclude query string with base excludes and your excludes
*/
function excludeString(toRetrieve) {
var query,
blocks = ['alerts', 'currently', 'daily', 'flags', 'hourly', 'minutely'],
includeIndex = blocks.indexOf(toRetrieve);
blocks.splice(includeIndex, 1);
query = blocks.join(',');
return config.baseExclude + query;
}
/**
* Get query string for additional API options
* @param {object} options
* @returns {string} additional options query string
*/
function optionsString(options) {
var defaults = {
extend: false
},
atts = extend({}, defaults, options),
query = '';
if (options) {
// parse extend option
if (atts.extend) {
query += '&extend=hourly';
}
}
return query;
}
function extend(out) {
out = out || {};
for (var i = 1; i < arguments.length; i++) {
if (!arguments[i]) {
continue;
}
for (var key in arguments[i]) {
if (arguments[i].hasOwnProperty(key)) {
out[key] = arguments[i][key];
}
}
}
return out;
}
/**
* Perform http jsonp request for weather data
* @param {number} latitude - position latitude
* @param {number} longitude - position longitude
* @param {string} query - additional request params query string
* @param {number} time - timestamp for timemachine requests
* @returns {promise} - resolves to weather data object
*/
function fetch(latitude, longitude, query, time) {
if (!latitude || !longitude) {
console.warn("no latitude or longitude sent to weather api");
}
var time = time ? ', ' + time : '',
url = [config.baseUri, apiKey, '/', latitude, ',', longitude, time, '?units=', units, '&lang=', language, query].join('');
return $http
.jsonp(url)
.then(function (results) {
// check response code
if (parseInt(results.status) === 200) {
return results.data;
} else {
return $q.reject(results);
}
})
.catch(function (data, status, headers, config) {
return $q.reject(status);
});
}
/**
* Return the us response units
* @returns {object} units
*/
function getUsUnits() {
return {
nearestStormDistance: 'mi',
precipIntensity: 'in/h',
precipIntensityMax: 'in/h',
precipAccumulation: 'in',
temperature: 'f',
temperatureMin: 'f',
temperatureMax: 'f',
apparentTemperature: 'f',
dewPoint: 'f',
windSpeed: 'mph',
pressure: 'mbar',
visibility: 'mi'
};
}
/**
* Return the si response units
* @returns {object} units
*/
function getSiUnits() {
return {
nearestStormDistance: 'km',
precipIntensity: 'mm/h',
precipIntensityMax: 'mm/h',
precipAccumulation: 'cm',
temperature: 'c',
temperatureMin: 'c',
temperatureMax: 'c',
apparentTemperature: 'c',
dewPoint: 'c',
windSpeed: 'mps',
pressure: 'hPa',
visibility: 'km'
};
}
/**
* Return ca response units
* @returns {object} units
*/
function getCaUnits() {
var unitsObject = getUsUnits();
unitsObject.windSpeed = 'km/h';
return unitsObject;
}
/**
* Return uk2 response units
* @returns {object} units
*/
function getUk2Units() {
var unitsObject = getSiUnits();
unitsObject.nearestStormDistance = unitsObject.visibility = 'mi';
unitsObject.windSpeed = 'mph';
return unitsObject;
}
}];
}
/**
* Dark Sky weather-icons directive
* @example <dark-sky-icon icon="{{ icon }}"></dark-sky-icon>
* @see {@link http://erikflowers.github.io/weather-icons}
*/
function darkSkyIcon(darkSky) {
return {
restrict: 'E',
scope: {
icon: '@'
},
template: '<i class="wi wi-forecast-io-{{ icon }} wi-dark-sky-{{ icon }}"></i>'
};
}
})();