@mharj/openweathermap 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,903 +1,954 @@
1
- // src/types/v2/Icon.ts
1
+ import { Err, Ok, Option, Result } from "@luolapeikko/result-option";
2
2
  import { z } from "zod";
3
- var dayIconList = ["01d", "02d", "03d", "04d", "09d", "10d", "11d", "13d", "50d"];
4
- var dayIconListSchema = z.enum(dayIconList);
5
- var nightIconList = ["01n", "02n", "03n", "04n", "09n", "10n", "11n", "13n", "50n"];
6
- var nightIconListSchema = z.enum(nightIconList);
7
- var iconSchema = z.union([dayIconListSchema, nightIconListSchema]);
8
3
 
9
- // src/types/v2/weatherIdGroup.ts
10
- import { undefinedOptionWrap } from "@luolapeikko/result-option";
11
- import { z as z2 } from "zod";
12
- var weatherIdGroup = [
13
- {
14
- id: 200,
15
- group: "thunderstorm",
16
- description: "thunderstorm_with_light_rain"
17
- },
18
- {
19
- id: 201,
20
- group: "thunderstorm",
21
- description: "thunderstorm_with_rain"
22
- },
23
- {
24
- id: 202,
25
- group: "thunderstorm",
26
- description: "thunderstorm_with_heavy_rain"
27
- },
28
- {
29
- id: 210,
30
- group: "thunderstorm",
31
- description: "light_thunderstorm"
32
- },
33
- {
34
- id: 211,
35
- group: "thunderstorm",
36
- description: "thunderstorm"
37
- },
38
- {
39
- id: 212,
40
- group: "thunderstorm",
41
- description: "heavy_thunderstorm"
42
- },
43
- {
44
- id: 221,
45
- group: "thunderstorm",
46
- description: "ragged_thunderstorm"
47
- },
48
- {
49
- id: 230,
50
- group: "thunderstorm",
51
- description: "thunderstorm_with_light_drizzle"
52
- },
53
- {
54
- id: 231,
55
- group: "thunderstorm",
56
- description: "thunderstorm_with_drizzle"
57
- },
58
- {
59
- id: 232,
60
- group: "thunderstorm",
61
- description: "thunderstorm_with_heavy_drizzle"
62
- },
63
- {
64
- id: 300,
65
- group: "drizzle",
66
- description: "light_intensity_drizzle"
67
- },
68
- {
69
- id: 301,
70
- group: "drizzle",
71
- description: "drizzle"
72
- },
73
- {
74
- id: 302,
75
- group: "drizzle",
76
- description: "heavy_intensity_drizzle"
77
- },
78
- {
79
- id: 310,
80
- group: "drizzle",
81
- description: "light_intensity_drizzle_rain"
82
- },
83
- {
84
- id: 311,
85
- group: "drizzle",
86
- description: "drizzle_rain"
87
- },
88
- {
89
- id: 312,
90
- group: "drizzle",
91
- description: "heavy_intensity_drizzle_rain"
92
- },
93
- {
94
- id: 313,
95
- group: "drizzle",
96
- description: "shower_rain_and_drizzle"
97
- },
98
- {
99
- id: 314,
100
- group: "drizzle",
101
- description: "heavy_shower_rain_and_drizzle"
102
- },
103
- {
104
- id: 321,
105
- group: "drizzle",
106
- description: "shower_drizzle"
107
- },
108
- {
109
- id: 500,
110
- group: "rain",
111
- description: "light_rain"
112
- },
113
- {
114
- id: 501,
115
- group: "rain",
116
- description: "moderate_rain"
117
- },
118
- {
119
- id: 502,
120
- group: "rain",
121
- description: "heavy_intensity_rain"
122
- },
123
- {
124
- id: 503,
125
- group: "rain",
126
- description: "very_heavy_rain"
127
- },
128
- {
129
- id: 504,
130
- group: "rain",
131
- description: "extreme_rain"
132
- },
133
- {
134
- id: 511,
135
- group: "rain",
136
- description: "freezing_rain"
137
- },
138
- {
139
- id: 520,
140
- group: "rain",
141
- description: "light_intensity_shower_rain"
142
- },
143
- {
144
- id: 521,
145
- group: "rain",
146
- description: "shower_rain"
147
- },
148
- {
149
- id: 522,
150
- group: "rain",
151
- description: "heavy_intensity_shower_rain"
152
- },
153
- {
154
- id: 531,
155
- group: "rain",
156
- description: "ragged_shower_rain"
157
- },
158
- {
159
- id: 600,
160
- group: "snow",
161
- description: "light_snow"
162
- },
163
- {
164
- id: 601,
165
- group: "snow",
166
- description: "snow"
167
- },
168
- {
169
- id: 602,
170
- group: "snow",
171
- description: "heavy_snow"
172
- },
173
- {
174
- id: 611,
175
- group: "snow",
176
- description: "sleet"
177
- },
178
- {
179
- id: 612,
180
- group: "snow",
181
- description: "light_shower_sleet"
182
- },
183
- {
184
- id: 613,
185
- group: "snow",
186
- description: "shower_sleet"
187
- },
188
- {
189
- id: 615,
190
- group: "snow",
191
- description: "light_rain_and_snow"
192
- },
193
- {
194
- id: 616,
195
- group: "snow",
196
- description: "rain_and_snow"
197
- },
198
- {
199
- id: 620,
200
- group: "snow",
201
- description: "light_shower_snow"
202
- },
203
- {
204
- id: 621,
205
- group: "snow",
206
- description: "shower_snow"
207
- },
208
- {
209
- id: 622,
210
- group: "snow",
211
- description: "heavy_shower_snow"
212
- },
213
- {
214
- id: 701,
215
- group: "atmosphere",
216
- description: "mist"
217
- },
218
- {
219
- id: 711,
220
- group: "atmosphere",
221
- description: "smoke"
222
- },
223
- {
224
- id: 721,
225
- group: "atmosphere",
226
- description: "haze"
227
- },
228
- {
229
- id: 731,
230
- group: "atmosphere",
231
- description: "sand_dust_whirls"
232
- },
233
- {
234
- id: 741,
235
- group: "atmosphere",
236
- description: "fog"
237
- },
238
- {
239
- id: 751,
240
- group: "atmosphere",
241
- description: "sand"
242
- },
243
- {
244
- id: 761,
245
- group: "atmosphere",
246
- description: "dust"
247
- },
248
- {
249
- id: 762,
250
- group: "atmosphere",
251
- description: "volcanic_ash"
252
- },
253
- {
254
- id: 771,
255
- group: "atmosphere",
256
- description: "squalls"
257
- },
258
- {
259
- id: 781,
260
- group: "atmosphere",
261
- description: "tornado"
262
- },
263
- {
264
- id: 800,
265
- group: "clear",
266
- description: "clear_sky"
267
- },
268
- {
269
- id: 801,
270
- group: "clouds",
271
- description: "few_clouds_11-25_percent"
272
- },
273
- {
274
- id: 802,
275
- group: "clouds",
276
- description: "scattered_clouds_25-50_percent"
277
- },
278
- {
279
- id: 803,
280
- group: "clouds",
281
- description: "broken_clouds_51-84_percent"
282
- },
283
- {
284
- id: 804,
285
- group: "clouds",
286
- description: "overcast_clouds_85-100_percent"
287
- }
4
+ //#region src/lib/fetchUtils.ts
5
+ /**
6
+ * Ensures that the error is a DOMException or TypeError.
7
+ * @internal
8
+ */
9
+ function fetchErrorWrapper(err) {
10
+ if (err instanceof DOMException || err instanceof TypeError) return err;
11
+ else return /* @__PURE__ */ new TypeError(`Unknown error: ${String(err)}`);
12
+ }
13
+
14
+ //#endregion
15
+ //#region src/types/v2/Icon.ts
16
+ /**
17
+ * @internal
18
+ */
19
+ const dayIconListSchema = z.enum([
20
+ "01d",
21
+ "02d",
22
+ "03d",
23
+ "04d",
24
+ "09d",
25
+ "10d",
26
+ "11d",
27
+ "13d",
28
+ "50d"
29
+ ]);
30
+ /**
31
+ * @internal
32
+ */
33
+ const nightIconListSchema = z.enum([
34
+ "01n",
35
+ "02n",
36
+ "03n",
37
+ "04n",
38
+ "09n",
39
+ "10n",
40
+ "11n",
41
+ "13n",
42
+ "50n"
43
+ ]);
44
+ /**
45
+ * @internal
46
+ */
47
+ const iconSchema = z.union([dayIconListSchema, nightIconListSchema]);
48
+
49
+ //#endregion
50
+ //#region src/types/v2/weatherIdGroup.ts
51
+ /**
52
+ * This is a list of weather ids, groups and descriptions from OpenWeatherMap API
53
+ */
54
+ const weatherIdGroup = [
55
+ {
56
+ id: 200,
57
+ group: "thunderstorm",
58
+ description: "thunderstorm_with_light_rain"
59
+ },
60
+ {
61
+ id: 201,
62
+ group: "thunderstorm",
63
+ description: "thunderstorm_with_rain"
64
+ },
65
+ {
66
+ id: 202,
67
+ group: "thunderstorm",
68
+ description: "thunderstorm_with_heavy_rain"
69
+ },
70
+ {
71
+ id: 210,
72
+ group: "thunderstorm",
73
+ description: "light_thunderstorm"
74
+ },
75
+ {
76
+ id: 211,
77
+ group: "thunderstorm",
78
+ description: "thunderstorm"
79
+ },
80
+ {
81
+ id: 212,
82
+ group: "thunderstorm",
83
+ description: "heavy_thunderstorm"
84
+ },
85
+ {
86
+ id: 221,
87
+ group: "thunderstorm",
88
+ description: "ragged_thunderstorm"
89
+ },
90
+ {
91
+ id: 230,
92
+ group: "thunderstorm",
93
+ description: "thunderstorm_with_light_drizzle"
94
+ },
95
+ {
96
+ id: 231,
97
+ group: "thunderstorm",
98
+ description: "thunderstorm_with_drizzle"
99
+ },
100
+ {
101
+ id: 232,
102
+ group: "thunderstorm",
103
+ description: "thunderstorm_with_heavy_drizzle"
104
+ },
105
+ {
106
+ id: 300,
107
+ group: "drizzle",
108
+ description: "light_intensity_drizzle"
109
+ },
110
+ {
111
+ id: 301,
112
+ group: "drizzle",
113
+ description: "drizzle"
114
+ },
115
+ {
116
+ id: 302,
117
+ group: "drizzle",
118
+ description: "heavy_intensity_drizzle"
119
+ },
120
+ {
121
+ id: 310,
122
+ group: "drizzle",
123
+ description: "light_intensity_drizzle_rain"
124
+ },
125
+ {
126
+ id: 311,
127
+ group: "drizzle",
128
+ description: "drizzle_rain"
129
+ },
130
+ {
131
+ id: 312,
132
+ group: "drizzle",
133
+ description: "heavy_intensity_drizzle_rain"
134
+ },
135
+ {
136
+ id: 313,
137
+ group: "drizzle",
138
+ description: "shower_rain_and_drizzle"
139
+ },
140
+ {
141
+ id: 314,
142
+ group: "drizzle",
143
+ description: "heavy_shower_rain_and_drizzle"
144
+ },
145
+ {
146
+ id: 321,
147
+ group: "drizzle",
148
+ description: "shower_drizzle"
149
+ },
150
+ {
151
+ id: 500,
152
+ group: "rain",
153
+ description: "light_rain"
154
+ },
155
+ {
156
+ id: 501,
157
+ group: "rain",
158
+ description: "moderate_rain"
159
+ },
160
+ {
161
+ id: 502,
162
+ group: "rain",
163
+ description: "heavy_intensity_rain"
164
+ },
165
+ {
166
+ id: 503,
167
+ group: "rain",
168
+ description: "very_heavy_rain"
169
+ },
170
+ {
171
+ id: 504,
172
+ group: "rain",
173
+ description: "extreme_rain"
174
+ },
175
+ {
176
+ id: 511,
177
+ group: "rain",
178
+ description: "freezing_rain"
179
+ },
180
+ {
181
+ id: 520,
182
+ group: "rain",
183
+ description: "light_intensity_shower_rain"
184
+ },
185
+ {
186
+ id: 521,
187
+ group: "rain",
188
+ description: "shower_rain"
189
+ },
190
+ {
191
+ id: 522,
192
+ group: "rain",
193
+ description: "heavy_intensity_shower_rain"
194
+ },
195
+ {
196
+ id: 531,
197
+ group: "rain",
198
+ description: "ragged_shower_rain"
199
+ },
200
+ {
201
+ id: 600,
202
+ group: "snow",
203
+ description: "light_snow"
204
+ },
205
+ {
206
+ id: 601,
207
+ group: "snow",
208
+ description: "snow"
209
+ },
210
+ {
211
+ id: 602,
212
+ group: "snow",
213
+ description: "heavy_snow"
214
+ },
215
+ {
216
+ id: 611,
217
+ group: "snow",
218
+ description: "sleet"
219
+ },
220
+ {
221
+ id: 612,
222
+ group: "snow",
223
+ description: "light_shower_sleet"
224
+ },
225
+ {
226
+ id: 613,
227
+ group: "snow",
228
+ description: "shower_sleet"
229
+ },
230
+ {
231
+ id: 615,
232
+ group: "snow",
233
+ description: "light_rain_and_snow"
234
+ },
235
+ {
236
+ id: 616,
237
+ group: "snow",
238
+ description: "rain_and_snow"
239
+ },
240
+ {
241
+ id: 620,
242
+ group: "snow",
243
+ description: "light_shower_snow"
244
+ },
245
+ {
246
+ id: 621,
247
+ group: "snow",
248
+ description: "shower_snow"
249
+ },
250
+ {
251
+ id: 622,
252
+ group: "snow",
253
+ description: "heavy_shower_snow"
254
+ },
255
+ {
256
+ id: 701,
257
+ group: "atmosphere",
258
+ description: "mist"
259
+ },
260
+ {
261
+ id: 711,
262
+ group: "atmosphere",
263
+ description: "smoke"
264
+ },
265
+ {
266
+ id: 721,
267
+ group: "atmosphere",
268
+ description: "haze"
269
+ },
270
+ {
271
+ id: 731,
272
+ group: "atmosphere",
273
+ description: "sand_dust_whirls"
274
+ },
275
+ {
276
+ id: 741,
277
+ group: "atmosphere",
278
+ description: "fog"
279
+ },
280
+ {
281
+ id: 751,
282
+ group: "atmosphere",
283
+ description: "sand"
284
+ },
285
+ {
286
+ id: 761,
287
+ group: "atmosphere",
288
+ description: "dust"
289
+ },
290
+ {
291
+ id: 762,
292
+ group: "atmosphere",
293
+ description: "volcanic_ash"
294
+ },
295
+ {
296
+ id: 771,
297
+ group: "atmosphere",
298
+ description: "squalls"
299
+ },
300
+ {
301
+ id: 781,
302
+ group: "atmosphere",
303
+ description: "tornado"
304
+ },
305
+ {
306
+ id: 800,
307
+ group: "clear",
308
+ description: "clear_sky"
309
+ },
310
+ {
311
+ id: 801,
312
+ group: "clouds",
313
+ description: "few_clouds_11-25_percent"
314
+ },
315
+ {
316
+ id: 802,
317
+ group: "clouds",
318
+ description: "scattered_clouds_25-50_percent"
319
+ },
320
+ {
321
+ id: 803,
322
+ group: "clouds",
323
+ description: "broken_clouds_51-84_percent"
324
+ },
325
+ {
326
+ id: 804,
327
+ group: "clouds",
328
+ description: "overcast_clouds_85-100_percent"
329
+ }
288
330
  ];
289
- var weatherIdSchema = z2.custom((val) => {
290
- if (typeof val !== "number") {
291
- return { message: "Expected a number", success: false };
292
- }
293
- if (!weatherIdGroup.find((x) => x.id === val)) {
294
- return { message: "Expected a valid weather id", success: false };
295
- }
296
- return val;
331
+ /**
332
+ * Weather id schema
333
+ * @internal
334
+ */
335
+ const weatherIdSchema = z.custom((val) => {
336
+ if (typeof val !== "number") return {
337
+ message: "Expected a number",
338
+ success: false
339
+ };
340
+ if (!weatherIdGroup.find((x) => x.id === val)) return {
341
+ message: "Expected a valid weather id",
342
+ success: false
343
+ };
344
+ return val;
297
345
  });
346
+ /**
347
+ * get weather description key from weather id
348
+ * @param id - weather id
349
+ * @returns {Option<WeatherDescription>} option for weather description key
350
+ * @example
351
+ * const weatherComponent = ({data}) => {
352
+ * const key = getWeatherV2Description(data.weather[0]?.id).unwrapOr('unknown');
353
+ * return (
354
+ * <div>
355
+ * {t(`weather:${key}`}
356
+ * </div>
357
+ * );
358
+ * }
359
+ */
298
360
  function getWeatherV2Description(id) {
299
- return undefinedOptionWrap(weatherIdGroup.find((x) => x.id === id)?.description);
361
+ return Option.fromNullish(weatherIdGroup.find((x) => x.id === id)?.description);
300
362
  }
301
363
 
302
- // src/types/v2/index.ts
303
- import { z as z4 } from "zod";
304
-
305
- // src/types/v2/Language.ts
306
- import { z as z3 } from "zod";
307
- var langCodes = [
308
- "af",
309
- "al",
310
- "ar",
311
- "az",
312
- "bg",
313
- "ca",
314
- "cz",
315
- "da",
316
- "de",
317
- "el",
318
- "en",
319
- "eu",
320
- "fa",
321
- "fi",
322
- "fr",
323
- "gl",
324
- "he",
325
- "hi",
326
- "hr",
327
- "hu",
328
- "id",
329
- "it",
330
- "ja",
331
- "kr",
332
- "la",
333
- "lt",
334
- "mk",
335
- "no",
336
- "nl",
337
- "pl",
338
- "pt",
339
- "pt",
340
- "ro",
341
- "ru",
342
- "sv",
343
- "sk",
344
- "sl",
345
- "sp",
346
- "sr",
347
- "th",
348
- "tr",
349
- "ua",
350
- "vi",
351
- "zh_cn",
352
- "zh_tw",
353
- "zu"
364
+ //#endregion
365
+ //#region src/types/v2/Language.ts
366
+ const langCodes = [
367
+ "af",
368
+ "al",
369
+ "ar",
370
+ "az",
371
+ "bg",
372
+ "ca",
373
+ "cz",
374
+ "da",
375
+ "de",
376
+ "el",
377
+ "en",
378
+ "eu",
379
+ "fa",
380
+ "fi",
381
+ "fr",
382
+ "gl",
383
+ "he",
384
+ "hi",
385
+ "hr",
386
+ "hu",
387
+ "id",
388
+ "it",
389
+ "ja",
390
+ "kr",
391
+ "la",
392
+ "lt",
393
+ "mk",
394
+ "no",
395
+ "nl",
396
+ "pl",
397
+ "pt",
398
+ "pt",
399
+ "ro",
400
+ "ru",
401
+ "sv",
402
+ "sk",
403
+ "sl",
404
+ "sp",
405
+ "sr",
406
+ "th",
407
+ "tr",
408
+ "ua",
409
+ "vi",
410
+ "zh_cn",
411
+ "zh_tw",
412
+ "zu"
354
413
  ];
355
- var langCodeSchema = z3.enum(langCodes);
414
+ const langCodeSchema = z.enum(langCodes);
356
415
 
357
- // src/types/v2/index.ts
358
- var coordSchema = z4.object({
359
- lon: z4.number(),
360
- lat: z4.number()
416
+ //#endregion
417
+ //#region src/types/v2/index.ts
418
+ const coordSchema = z.object({
419
+ lon: z.number(),
420
+ lat: z.number()
361
421
  });
362
- var weatherSchema = z4.object({
363
- description: z4.string(),
364
- icon: iconSchema,
365
- id: weatherIdSchema,
366
- main: z4.string()
422
+ const weatherSchema = z.object({
423
+ description: z.string(),
424
+ icon: iconSchema,
425
+ id: weatherIdSchema,
426
+ main: z.string()
367
427
  });
368
- var mainSchema = z4.object({
369
- grnd_level: z4.number().optional(),
370
- humidity: z4.number(),
371
- pressure: z4.number(),
372
- sea_level: z4.number().optional(),
373
- temp: z4.number(),
374
- temp_max: z4.number(),
375
- temp_min: z4.number()
428
+ const mainSchema = z.object({
429
+ grnd_level: z.number().optional(),
430
+ humidity: z.number(),
431
+ pressure: z.number(),
432
+ sea_level: z.number().optional(),
433
+ temp: z.number(),
434
+ temp_max: z.number(),
435
+ temp_min: z.number()
376
436
  });
377
- var windSchema = z4.object({
378
- speed: z4.number(),
379
- deg: z4.number()
437
+ const windSchema = z.object({
438
+ speed: z.number(),
439
+ deg: z.number()
380
440
  });
381
- var rainSchema = z4.object({
382
- "1h": z4.number().optional(),
383
- "3h": z4.number().optional()
441
+ const rainSchema = z.object({
442
+ "1h": z.number().optional(),
443
+ "3h": z.number().optional()
384
444
  });
385
- var snowSchema = z4.object({
386
- "1h": z4.number().optional(),
387
- "3h": z4.number().optional()
445
+ const snowSchema = z.object({
446
+ "1h": z.number().optional(),
447
+ "3h": z.number().optional()
388
448
  });
389
- var sysSchema = z4.object({
390
- country: z4.string(),
391
- id: z4.number().optional(),
392
- message: z4.number().optional(),
393
- sunrise: z4.number(),
394
- sunset: z4.number(),
395
- type: z4.number().optional()
449
+ const sysSchema = z.object({
450
+ country: z.string(),
451
+ id: z.number().optional(),
452
+ message: z.number().optional(),
453
+ sunrise: z.number(),
454
+ sunset: z.number(),
455
+ type: z.number().optional()
396
456
  });
397
- var weatherDataV2Schema = z4.object({
398
- base: z4.string(),
399
- clouds: z4.object({
400
- all: z4.number()
401
- }),
402
- cod: z4.number(),
403
- coord: coordSchema,
404
- dt: z4.number(),
405
- id: z4.number(),
406
- main: mainSchema,
407
- name: z4.string(),
408
- rain: rainSchema.optional(),
409
- snow: snowSchema.optional(),
410
- sys: sysSchema,
411
- timezone: z4.number(),
412
- visibility: z4.number(),
413
- weather: z4.array(weatherSchema),
414
- wind: windSchema
457
+ /**
458
+ * @internal
459
+ */
460
+ const weatherDataV2Schema = z.object({
461
+ base: z.string(),
462
+ clouds: z.object({ all: z.number() }),
463
+ cod: z.number(),
464
+ coord: coordSchema,
465
+ dt: z.number(),
466
+ id: z.number(),
467
+ main: mainSchema,
468
+ name: z.string(),
469
+ rain: rainSchema.optional(),
470
+ snow: snowSchema.optional(),
471
+ sys: sysSchema,
472
+ timezone: z.number(),
473
+ visibility: z.number(),
474
+ weather: z.array(weatherSchema),
475
+ wind: windSchema
415
476
  });
416
477
  function isWeatherDataV2(data) {
417
- return weatherDataV2Schema.safeParse(data).success;
478
+ return weatherDataV2Schema.safeParse(data).success;
418
479
  }
419
480
  function assertWeatherDataV2(data) {
420
- weatherDataV2Schema.parse(data);
481
+ weatherDataV2Schema.parse(data);
421
482
  }
422
483
 
423
- // src/types/ISO3166-Countries.ts
424
- import { z as z5 } from "zod";
425
- var CountryCodeList = [
426
- "af",
427
- "ax",
428
- "al",
429
- "dz",
430
- "as",
431
- "ad",
432
- "ao",
433
- "ai",
434
- "aq",
435
- "ag",
436
- "ar",
437
- "am",
438
- "aw",
439
- "au",
440
- "at",
441
- "az",
442
- "bs",
443
- "bh",
444
- "bd",
445
- "bb",
446
- "by",
447
- "be",
448
- "bz",
449
- "bj",
450
- "bm",
451
- "bt",
452
- "bo",
453
- "bq",
454
- "ba",
455
- "bw",
456
- "bv",
457
- "br",
458
- "io",
459
- "bn",
460
- "bg",
461
- "bf",
462
- "bi",
463
- "kh",
464
- "cm",
465
- "ca",
466
- "cv",
467
- "ky",
468
- "cf",
469
- "td",
470
- "cl",
471
- "cn",
472
- "cx",
473
- "cc",
474
- "co",
475
- "km",
476
- "cg",
477
- "cd",
478
- "ck",
479
- "cr",
480
- "ci",
481
- "hr",
482
- "cu",
483
- "cw",
484
- "cy",
485
- "cz",
486
- "dk",
487
- "dj",
488
- "dm",
489
- "do",
490
- "ec",
491
- "eg",
492
- "sv",
493
- "gq",
494
- "er",
495
- "ee",
496
- "et",
497
- "fk",
498
- "fo",
499
- "fj",
500
- "fi",
501
- "fr",
502
- "gf",
503
- "pf",
504
- "tf",
505
- "ga",
506
- "gm",
507
- "ge",
508
- "de",
509
- "gh",
510
- "gi",
511
- "gr",
512
- "gl",
513
- "gd",
514
- "gp",
515
- "gu",
516
- "gt",
517
- "gg",
518
- "gn",
519
- "gw",
520
- "gy",
521
- "ht",
522
- "hm",
523
- "va",
524
- "hn",
525
- "hk",
526
- "hu",
527
- "is",
528
- "in",
529
- "id",
530
- "ir",
531
- "iq",
532
- "ie",
533
- "im",
534
- "il",
535
- "it",
536
- "jm",
537
- "jp",
538
- "je",
539
- "jo",
540
- "kz",
541
- "ke",
542
- "ki",
543
- "kp",
544
- "kr",
545
- "kw",
546
- "kg",
547
- "la",
548
- "lv",
549
- "lb",
550
- "ls",
551
- "lr",
552
- "ly",
553
- "li",
554
- "lt",
555
- "lu",
556
- "mo",
557
- "mk",
558
- "mg",
559
- "mw",
560
- "my",
561
- "mv",
562
- "ml",
563
- "mt",
564
- "mh",
565
- "mq",
566
- "mr",
567
- "mu",
568
- "yt",
569
- "mx",
570
- "fm",
571
- "md",
572
- "mc",
573
- "mn",
574
- "me",
575
- "ms",
576
- "ma",
577
- "mz",
578
- "mm",
579
- "na",
580
- "nr",
581
- "np",
582
- "nl",
583
- "nc",
584
- "nz",
585
- "ni",
586
- "ne",
587
- "ng",
588
- "nu",
589
- "nf",
590
- "mp",
591
- "no",
592
- "om",
593
- "pk",
594
- "pw",
595
- "ps",
596
- "pa",
597
- "pg",
598
- "py",
599
- "pe",
600
- "ph",
601
- "pn",
602
- "pl",
603
- "pt",
604
- "pr",
605
- "qa",
606
- "re",
607
- "ro",
608
- "ru",
609
- "rw",
610
- "bl",
611
- "sh",
612
- "kn",
613
- "lc",
614
- "mf",
615
- "pm",
616
- "vc",
617
- "ws",
618
- "sm",
619
- "st",
620
- "sa",
621
- "sn",
622
- "rs",
623
- "sc",
624
- "sl",
625
- "sg",
626
- "sx",
627
- "sk",
628
- "si",
629
- "sb",
630
- "so",
631
- "za",
632
- "gs",
633
- "ss",
634
- "es",
635
- "lk",
636
- "sd",
637
- "sr",
638
- "sj",
639
- "sz",
640
- "se",
641
- "ch",
642
- "sy",
643
- "tw",
644
- "tj",
645
- "tz",
646
- "th",
647
- "tl",
648
- "tg",
649
- "tk",
650
- "to",
651
- "tt",
652
- "tn",
653
- "tr",
654
- "tm",
655
- "tc",
656
- "tv",
657
- "ug",
658
- "ua",
659
- "ae",
660
- "gb",
661
- "us",
662
- "um",
663
- "uy",
664
- "uz",
665
- "vu",
666
- "ve",
667
- "vn",
668
- "vg",
669
- "vi",
670
- "wf",
671
- "eh",
672
- "ye",
673
- "zm",
674
- "zw"
484
+ //#endregion
485
+ //#region src/types/ISO3166-Countries.ts
486
+ const CountryCodeList = [
487
+ "af",
488
+ "ax",
489
+ "al",
490
+ "dz",
491
+ "as",
492
+ "ad",
493
+ "ao",
494
+ "ai",
495
+ "aq",
496
+ "ag",
497
+ "ar",
498
+ "am",
499
+ "aw",
500
+ "au",
501
+ "at",
502
+ "az",
503
+ "bs",
504
+ "bh",
505
+ "bd",
506
+ "bb",
507
+ "by",
508
+ "be",
509
+ "bz",
510
+ "bj",
511
+ "bm",
512
+ "bt",
513
+ "bo",
514
+ "bq",
515
+ "ba",
516
+ "bw",
517
+ "bv",
518
+ "br",
519
+ "io",
520
+ "bn",
521
+ "bg",
522
+ "bf",
523
+ "bi",
524
+ "kh",
525
+ "cm",
526
+ "ca",
527
+ "cv",
528
+ "ky",
529
+ "cf",
530
+ "td",
531
+ "cl",
532
+ "cn",
533
+ "cx",
534
+ "cc",
535
+ "co",
536
+ "km",
537
+ "cg",
538
+ "cd",
539
+ "ck",
540
+ "cr",
541
+ "ci",
542
+ "hr",
543
+ "cu",
544
+ "cw",
545
+ "cy",
546
+ "cz",
547
+ "dk",
548
+ "dj",
549
+ "dm",
550
+ "do",
551
+ "ec",
552
+ "eg",
553
+ "sv",
554
+ "gq",
555
+ "er",
556
+ "ee",
557
+ "et",
558
+ "fk",
559
+ "fo",
560
+ "fj",
561
+ "fi",
562
+ "fr",
563
+ "gf",
564
+ "pf",
565
+ "tf",
566
+ "ga",
567
+ "gm",
568
+ "ge",
569
+ "de",
570
+ "gh",
571
+ "gi",
572
+ "gr",
573
+ "gl",
574
+ "gd",
575
+ "gp",
576
+ "gu",
577
+ "gt",
578
+ "gg",
579
+ "gn",
580
+ "gw",
581
+ "gy",
582
+ "ht",
583
+ "hm",
584
+ "va",
585
+ "hn",
586
+ "hk",
587
+ "hu",
588
+ "is",
589
+ "in",
590
+ "id",
591
+ "ir",
592
+ "iq",
593
+ "ie",
594
+ "im",
595
+ "il",
596
+ "it",
597
+ "jm",
598
+ "jp",
599
+ "je",
600
+ "jo",
601
+ "kz",
602
+ "ke",
603
+ "ki",
604
+ "kp",
605
+ "kr",
606
+ "kw",
607
+ "kg",
608
+ "la",
609
+ "lv",
610
+ "lb",
611
+ "ls",
612
+ "lr",
613
+ "ly",
614
+ "li",
615
+ "lt",
616
+ "lu",
617
+ "mo",
618
+ "mk",
619
+ "mg",
620
+ "mw",
621
+ "my",
622
+ "mv",
623
+ "ml",
624
+ "mt",
625
+ "mh",
626
+ "mq",
627
+ "mr",
628
+ "mu",
629
+ "yt",
630
+ "mx",
631
+ "fm",
632
+ "md",
633
+ "mc",
634
+ "mn",
635
+ "me",
636
+ "ms",
637
+ "ma",
638
+ "mz",
639
+ "mm",
640
+ "na",
641
+ "nr",
642
+ "np",
643
+ "nl",
644
+ "nc",
645
+ "nz",
646
+ "ni",
647
+ "ne",
648
+ "ng",
649
+ "nu",
650
+ "nf",
651
+ "mp",
652
+ "no",
653
+ "om",
654
+ "pk",
655
+ "pw",
656
+ "ps",
657
+ "pa",
658
+ "pg",
659
+ "py",
660
+ "pe",
661
+ "ph",
662
+ "pn",
663
+ "pl",
664
+ "pt",
665
+ "pr",
666
+ "qa",
667
+ "re",
668
+ "ro",
669
+ "ru",
670
+ "rw",
671
+ "bl",
672
+ "sh",
673
+ "kn",
674
+ "lc",
675
+ "mf",
676
+ "pm",
677
+ "vc",
678
+ "ws",
679
+ "sm",
680
+ "st",
681
+ "sa",
682
+ "sn",
683
+ "rs",
684
+ "sc",
685
+ "sl",
686
+ "sg",
687
+ "sx",
688
+ "sk",
689
+ "si",
690
+ "sb",
691
+ "so",
692
+ "za",
693
+ "gs",
694
+ "ss",
695
+ "es",
696
+ "lk",
697
+ "sd",
698
+ "sr",
699
+ "sj",
700
+ "sz",
701
+ "se",
702
+ "ch",
703
+ "sy",
704
+ "tw",
705
+ "tj",
706
+ "tz",
707
+ "th",
708
+ "tl",
709
+ "tg",
710
+ "tk",
711
+ "to",
712
+ "tt",
713
+ "tn",
714
+ "tr",
715
+ "tm",
716
+ "tc",
717
+ "tv",
718
+ "ug",
719
+ "ua",
720
+ "ae",
721
+ "gb",
722
+ "us",
723
+ "um",
724
+ "uy",
725
+ "uz",
726
+ "vu",
727
+ "ve",
728
+ "vn",
729
+ "vg",
730
+ "vi",
731
+ "wf",
732
+ "eh",
733
+ "ye",
734
+ "zm",
735
+ "zw"
675
736
  ];
676
- var CountryCodeSchema = z5.enum(CountryCodeList);
677
-
678
- // src/OpenWeatherV2.ts
679
- import { Err, Ok, safeAsyncResult, safeAsyncResultBuilder } from "@luolapeikko/result-option";
737
+ /**
738
+ * @internal
739
+ */
740
+ const CountryCodeSchema = z.enum(CountryCodeList);
680
741
 
681
- // src/lib/fetchUtils.ts
682
- function fetchErrorWrapper(err) {
683
- if (err instanceof DOMException || err instanceof TypeError) {
684
- return err;
685
- } else {
686
- return new TypeError(`Unknown error: ${String(err)}`);
687
- }
688
- }
689
-
690
- // src/OpenWeatherV2.ts
691
- var fetchResult = safeAsyncResultBuilder(fetch);
742
+ //#endregion
743
+ //#region src/OpenWeatherV2.ts
744
+ const fetchResult = Result.wrapAsyncFn(fetch);
692
745
  function toParams(data) {
693
- return Object.entries(data).reduce((acc, [key, value]) => {
694
- acc[key] = String(value);
695
- return acc;
696
- }, {});
746
+ return Object.entries(data).reduce((acc, [key, value]) => {
747
+ acc[key] = String(value);
748
+ return acc;
749
+ }, {});
697
750
  }
698
751
  function isJson(response) {
699
- const contentType = response.headers.get("content-type");
700
- return contentType && contentType.startsWith("application/json") || false;
752
+ return response.headers.get("content-type")?.startsWith("application/json") ?? false;
701
753
  }
702
754
  function isOpenWeatherError(data) {
703
- return typeof data === "object" && data !== null && "cod" in data && "message" in data;
755
+ return typeof data === "object" && data !== null && "cod" in data && "message" in data;
704
756
  }
705
- var defaultCommonOptions = {
706
- lang: "en",
707
- units: "standard"
757
+ const defaultCommonOptions = {
758
+ lang: "en",
759
+ units: "standard"
708
760
  };
709
761
  function buildOpts(opts) {
710
- return Object.assign({}, defaultCommonOptions, opts);
762
+ return Object.assign({}, defaultCommonOptions, opts);
711
763
  }
712
- var basePath = "https://api.openweathermap.org/data/2.5/weather";
764
+ const basePath = "https://api.openweathermap.org/data/2.5/weather";
713
765
  function buildUrl(params) {
714
- return `${basePath}?${params.toString()}`;
766
+ return `${basePath}?${params.toString()}`;
715
767
  }
716
768
  function buildLogUrl(params) {
717
- const logParams = new URLSearchParams(params);
718
- logParams.set("appid", "***");
719
- return buildUrl(logParams);
769
+ const logParams = new URLSearchParams(params);
770
+ logParams.set("appid", "***");
771
+ return buildUrl(logParams);
720
772
  }
721
- var defaultImplementation = {
722
- dataWeatherApi: async (params) => {
723
- const logUrl = buildLogUrl(params);
724
- const result = await fetchResult(buildUrl(params));
725
- if (!result.isOk) {
726
- return Err(result.err());
727
- }
728
- const res = result.ok();
729
- if (!res.ok) {
730
- if (isJson(res)) {
731
- const data2 = await res.json();
732
- if (isOpenWeatherError(data2)) {
733
- return Err(new TypeError(`OpenWeatherV2 error: ${data2.message} from ${logUrl}`));
734
- }
735
- }
736
- return Err(new TypeError(`OpenWeatherV2 http error: ${res.status} ${res.statusText} from ${logUrl}`));
737
- }
738
- if (!isJson(res)) {
739
- return Err(new TypeError(`OpenWeatherV2 response is not json payload from ${logUrl}`));
740
- }
741
- const jsonResult = await safeAsyncResult(res.json());
742
- if (!jsonResult.isOk) {
743
- return Err(jsonResult.err());
744
- }
745
- const data = jsonResult.ok();
746
- assertWeatherDataV2(data);
747
- return Ok(data);
748
- }
749
- };
773
+ const defaultImplementation = { dataWeatherApi: async (params) => {
774
+ const logUrl = buildLogUrl(params);
775
+ const result = await fetchResult(buildUrl(params));
776
+ if (!result.isOk) return Err(result.err());
777
+ const res = result.ok();
778
+ if (!res.ok) {
779
+ if (isJson(res)) {
780
+ const data = await res.json();
781
+ if (isOpenWeatherError(data)) return Err(/* @__PURE__ */ new TypeError(`OpenWeatherV2 error: ${data.message} from ${logUrl}`));
782
+ }
783
+ return Err(/* @__PURE__ */ new TypeError(`OpenWeatherV2 http error: ${res.status} ${res.statusText} from ${logUrl}`));
784
+ }
785
+ if (!isJson(res)) return Err(/* @__PURE__ */ new TypeError(`OpenWeatherV2 response is not json payload from ${logUrl}`));
786
+ const jsonResult = await Result.safeAsyncCall(() => res.json());
787
+ if (!jsonResult.isOk) return Err(jsonResult.err());
788
+ const data = jsonResult.ok();
789
+ assertWeatherDataV2(data);
790
+ return Ok(data);
791
+ } };
792
+ /**
793
+ * Open Weather V2 API
794
+ * @example
795
+ * const weather = new OpenWeatherV2('your-api-key');
796
+ *
797
+ * const cache = new ExpireCache<WeatherDataV2>(undefined, undefined, 900000); // data 15 minutes in cache
798
+ * const weather = new OpenWeatherV2(() => Promise.resolve('your-api-key'), cache);
799
+ *
800
+ * const data: WeatherDataV2 = (await weather.getWeatherById(2643743)).unwrap(); // throws if error
801
+ * const data: WeatherDataV2 | undefined = (await weather.getWeatherByCity('Helsinki', 'fi')).ok();
802
+ *
803
+ * const result: Result<WeatherDataV2> = await weather.getWeatherByLatLon(60.1699, 24.9384);
804
+ * result.match({
805
+ * Ok: (data: WeatherDataV2) => console.log(data),
806
+ * Err: (err: DOMException | TypeError) => console.error(err),
807
+ * });
808
+ *
809
+ * if(result.isOk) {
810
+ * const data: WeatherDataV2 = data.ok();
811
+ * } else {
812
+ * const err: DOMException | TypeError = data.err();
813
+ * }
814
+ * @since v0.0.1
815
+ */
750
816
  var OpenWeatherV2 = class {
751
- cache;
752
- loadableApiKey;
753
- apiHandler;
754
- fetchPromiseMap = /* @__PURE__ */ new Map();
755
- /**
756
- * OpenWeatherV2 constructor
757
- * @param {Loadable<string>} loadableApiKey - Loadable API key
758
- * @param {ICacheOrAsync<WeatherDataV2>=} cache - optional async cache implementation
759
- * @param {IOpenWeatherV2=} apiHandler - optional API handler implementation for mocking
760
- */
761
- constructor(loadableApiKey, cache, apiHandler = defaultImplementation) {
762
- this.loadableApiKey = loadableApiKey;
763
- this.cache = cache;
764
- this.apiHandler = apiHandler;
765
- }
766
- /**
767
- * get weather by Id
768
- * @param {number} id - Weather station ID
769
- * @param {OpenWeatherV2CommonOptions=} currentOpts - Common options, example ```{lang: 'fi', units: 'metric'}```, defaults ```{lang: 'en', units: 'standard'}```
770
- * @return {Promise<Result<WeatherDataV2, DOMException | TypeError>>} Weather data Result Promise
771
- * @example
772
- * const result: Result<WeatherDataV2, DOMException | TypeError> = await weather.getWeatherResultById(id: 564, {lang: 'fi'});
773
- * if (result.isOk) {
774
- * const weatherData: WeatherDataV2 = result.ok();
775
- * } else {
776
- * const error: DOMException | TypeError = result.err();
777
- * }
778
- */
779
- async getWeatherById(id, currentOpts = {}) {
780
- try {
781
- const opts = buildOpts(currentOpts);
782
- const cacheKey = this.buildBaseCacheKey(`id:${id}`, opts);
783
- let cacheEntry = this.cache && await this.cache.get(cacheKey);
784
- if (!cacheEntry) {
785
- const params = await this.buildBaseParams(opts);
786
- params.append("id", String(id));
787
- cacheEntry = await this.handleFetch(cacheKey, params, opts);
788
- }
789
- return Ok(cacheEntry);
790
- } catch (err) {
791
- return Err(fetchErrorWrapper(err));
792
- }
793
- }
794
- /**
795
- * get weather with city name and optional country code
796
- * @param {string} city - City name
797
- * @param {countryCode=} countryCode - Optional Country code
798
- * @param {OpenWeatherV2CommonOptions=} currentOpts - Common options, example ```{lang: 'fi', units: 'metric'}```, defaults ```{lang: 'en', units: 'standard'}```
799
- * @return {Promise<Result<WeatherDataV2, DOMException | TypeError>>} Weather data Result Promise
800
- * @example
801
- * const result: Result<WeatherDataV2, DOMException | TypeError> = await weather.getWeatherByCity('Helsinki', 'fi', {lang: 'fi'});
802
- * if (result.isOk) {
803
- * const weatherData: WeatherDataV2 = result.ok();
804
- * } else {
805
- * const error: DOMException | TypeError = result.err();
806
- * }
807
- */
808
- async getWeatherByCity(city, countryCode, currentOpts = {}) {
809
- try {
810
- const opts = buildOpts(currentOpts);
811
- const cacheKey = this.buildBaseCacheKey(`q:${city}:${countryCode}`, opts);
812
- let cacheEntry = this.cache && await this.cache.get(cacheKey);
813
- if (!cacheEntry) {
814
- const params = await this.buildBaseParams(opts);
815
- params.append("q", countryCode ? `${city},${countryCode}` : city);
816
- cacheEntry = await this.handleFetch(cacheKey, params, opts);
817
- }
818
- return Ok(cacheEntry);
819
- } catch (err) {
820
- return Err(fetchErrorWrapper(err));
821
- }
822
- }
823
- /**
824
- * get weather with latitude and longitude with Result
825
- * @param {number} lat - Latitude
826
- * @param {number} lon - Longitude
827
- * @param {OpenWeatherV2CommonOptions=} currentOpts - Common options, example ```{lang: 'fi', units: 'metric'}```, defaults ```{lang: 'en', units: 'standard'}```
828
- * @return {Promise<Result<WeatherDataV2, DOMException | TypeError>>} Weather data Result Promise
829
- * @example
830
- * const result: Result<WeatherDataV2, DOMException | TypeError> = await weather.getWeatherByLatLon(60.1699, 24.9384, {lang: 'fi'});
831
- * if (result.isOk) {
832
- * const weatherData: WeatherDataV2 = result.ok();
833
- * } else {
834
- * const error: DOMException | TypeError = result.err();
835
- * }
836
- */
837
- async getWeatherByLatLon(lat, lon, currentOpts = {}) {
838
- try {
839
- const opts = buildOpts(currentOpts);
840
- const cacheKey = this.buildBaseCacheKey(`latlon:${lat}:${lon}`, opts);
841
- let cacheEntry = this.cache && await this.cache.get(cacheKey);
842
- if (!cacheEntry) {
843
- const params = await this.buildBaseParams(opts);
844
- params.append("lat", String(lat));
845
- params.append("lon", String(lon));
846
- cacheEntry = await this.handleFetch(cacheKey, params, opts);
847
- }
848
- return Ok(cacheEntry);
849
- } catch (err) {
850
- return Err(fetchErrorWrapper(err));
851
- }
852
- }
853
- async buildBaseParams(options) {
854
- const apiKey = await (typeof this.loadableApiKey === "function" ? this.loadableApiKey() : this.loadableApiKey);
855
- const params = new URLSearchParams(toParams(options));
856
- params.append("appid", apiKey);
857
- return params;
858
- }
859
- /**
860
- * build base cache key
861
- * @param main - main cache key prefix
862
- * @param opts - OpenWeatherV2CommonOptions
863
- * @returns {string} cache key
864
- */
865
- buildBaseCacheKey(main, { lang, units }) {
866
- return `${main}:${lang}:${units}`;
867
- }
868
- async handleFetch(cacheKey, params, opts) {
869
- let promiseResult = this.fetchPromiseMap.get(cacheKey);
870
- if (!promiseResult) {
871
- promiseResult = this.apiHandler.dataWeatherApi(params);
872
- this.fetchPromiseMap.set(cacheKey, promiseResult);
873
- await promiseResult;
874
- this.fetchPromiseMap.delete(cacheKey);
875
- }
876
- const dataApiResult = await promiseResult;
877
- const data = dataApiResult.unwrap();
878
- assertWeatherDataV2(data);
879
- if (this.cache) {
880
- await this.cache.set(cacheKey, data);
881
- if (!cacheKey.startsWith("id:")) {
882
- await this.cache.set(this.buildBaseCacheKey(`id:${data.id}`, opts), data);
883
- }
884
- }
885
- return data;
886
- }
887
- };
888
- export {
889
- CountryCodeList,
890
- CountryCodeSchema,
891
- OpenWeatherV2,
892
- assertWeatherDataV2,
893
- fetchErrorWrapper,
894
- getWeatherV2Description,
895
- iconSchema,
896
- isWeatherDataV2,
897
- langCodeSchema,
898
- langCodes,
899
- weatherDataV2Schema,
900
- weatherIdGroup,
901
- weatherIdSchema
817
+ cache;
818
+ loadableApiKey;
819
+ apiHandler;
820
+ fetchPromiseMap = /* @__PURE__ */ new Map();
821
+ /**
822
+ * OpenWeatherV2 constructor
823
+ * @param {Loadable<string>} loadableApiKey - Loadable API key
824
+ * @param {ICacheOrAsync<WeatherDataV2>=} cache - optional async cache implementation
825
+ * @param {IOpenWeatherV2=} apiHandler - optional API handler implementation for mocking
826
+ */
827
+ constructor(loadableApiKey, cache, apiHandler = defaultImplementation) {
828
+ this.loadableApiKey = loadableApiKey;
829
+ this.cache = cache;
830
+ this.apiHandler = apiHandler;
831
+ }
832
+ /**
833
+ * get weather by Id
834
+ * @param {number} id - Weather station ID
835
+ * @param {OpenWeatherV2CommonOptions=} currentOpts - Common options, example ```{lang: 'fi', units: 'metric'}```, defaults ```{lang: 'en', units: 'standard'}```
836
+ * @return {Promise<Result<WeatherDataV2, DOMException | TypeError>>} Weather data Result Promise
837
+ * @example
838
+ * const result: Result<WeatherDataV2, DOMException | TypeError> = await weather.getWeatherResultById(id: 564, {lang: 'fi'});
839
+ * if (result.isOk) {
840
+ * const weatherData: WeatherDataV2 = result.ok();
841
+ * } else {
842
+ * const error: DOMException | TypeError = result.err();
843
+ * }
844
+ */
845
+ async getWeatherById(id, currentOpts = {}) {
846
+ try {
847
+ const opts = buildOpts(currentOpts);
848
+ const cacheKey = this.buildBaseCacheKey(`id:${id}`, opts);
849
+ let cacheEntry = this.cache && await this.cache.get(cacheKey);
850
+ if (!cacheEntry) {
851
+ const params = await this.buildBaseParams(opts);
852
+ params.append("id", String(id));
853
+ cacheEntry = await this.handleFetch(cacheKey, params, opts);
854
+ }
855
+ return Ok(cacheEntry);
856
+ } catch (err) {
857
+ return Err(fetchErrorWrapper(err));
858
+ }
859
+ }
860
+ /**
861
+ * get weather with city name and optional country code
862
+ * @param {string} city - City name
863
+ * @param {countryCode=} countryCode - Optional Country code
864
+ * @param {OpenWeatherV2CommonOptions=} currentOpts - Common options, example ```{lang: 'fi', units: 'metric'}```, defaults ```{lang: 'en', units: 'standard'}```
865
+ * @return {Promise<Result<WeatherDataV2, DOMException | TypeError>>} Weather data Result Promise
866
+ * @example
867
+ * const result: Result<WeatherDataV2, DOMException | TypeError> = await weather.getWeatherByCity('Helsinki', 'fi', {lang: 'fi'});
868
+ * if (result.isOk) {
869
+ * const weatherData: WeatherDataV2 = result.ok();
870
+ * } else {
871
+ * const error: DOMException | TypeError = result.err();
872
+ * }
873
+ */
874
+ async getWeatherByCity(city, countryCode, currentOpts = {}) {
875
+ try {
876
+ const opts = buildOpts(currentOpts);
877
+ const cacheKey = this.buildBaseCacheKey(`q:${city}:${countryCode}`, opts);
878
+ let cacheEntry = this.cache && await this.cache.get(cacheKey);
879
+ if (!cacheEntry) {
880
+ const params = await this.buildBaseParams(opts);
881
+ params.append("q", countryCode ? `${city},${countryCode}` : city);
882
+ cacheEntry = await this.handleFetch(cacheKey, params, opts);
883
+ }
884
+ return Ok(cacheEntry);
885
+ } catch (err) {
886
+ return Err(fetchErrorWrapper(err));
887
+ }
888
+ }
889
+ /**
890
+ * get weather with latitude and longitude with Result
891
+ * @param {number} lat - Latitude
892
+ * @param {number} lon - Longitude
893
+ * @param {OpenWeatherV2CommonOptions=} currentOpts - Common options, example ```{lang: 'fi', units: 'metric'}```, defaults ```{lang: 'en', units: 'standard'}```
894
+ * @return {Promise<Result<WeatherDataV2, DOMException | TypeError>>} Weather data Result Promise
895
+ * @example
896
+ * const result: Result<WeatherDataV2, DOMException | TypeError> = await weather.getWeatherByLatLon(60.1699, 24.9384, {lang: 'fi'});
897
+ * if (result.isOk) {
898
+ * const weatherData: WeatherDataV2 = result.ok();
899
+ * } else {
900
+ * const error: DOMException | TypeError = result.err();
901
+ * }
902
+ */
903
+ async getWeatherByLatLon(lat, lon, currentOpts = {}) {
904
+ try {
905
+ const opts = buildOpts(currentOpts);
906
+ const cacheKey = this.buildBaseCacheKey(`latlon:${lat}:${lon}`, opts);
907
+ let cacheEntry = this.cache && await this.cache.get(cacheKey);
908
+ if (!cacheEntry) {
909
+ const params = await this.buildBaseParams(opts);
910
+ params.append("lat", String(lat));
911
+ params.append("lon", String(lon));
912
+ cacheEntry = await this.handleFetch(cacheKey, params, opts);
913
+ }
914
+ return Ok(cacheEntry);
915
+ } catch (err) {
916
+ return Err(fetchErrorWrapper(err));
917
+ }
918
+ }
919
+ async buildBaseParams(options) {
920
+ const apiKey = await (typeof this.loadableApiKey === "function" ? this.loadableApiKey() : this.loadableApiKey);
921
+ const params = new URLSearchParams(toParams(options));
922
+ params.append("appid", apiKey);
923
+ return params;
924
+ }
925
+ /**
926
+ * build base cache key
927
+ * @param main - main cache key prefix
928
+ * @param opts - OpenWeatherV2CommonOptions
929
+ * @returns {string} cache key
930
+ */
931
+ buildBaseCacheKey(main, { lang, units }) {
932
+ return `${main}:${lang}:${units}`;
933
+ }
934
+ async handleFetch(cacheKey, params, opts) {
935
+ let promiseResult = this.fetchPromiseMap.get(cacheKey);
936
+ if (!promiseResult) {
937
+ promiseResult = this.apiHandler.dataWeatherApi(params);
938
+ this.fetchPromiseMap.set(cacheKey, promiseResult);
939
+ await promiseResult;
940
+ this.fetchPromiseMap.delete(cacheKey);
941
+ }
942
+ const data = (await promiseResult).unwrap();
943
+ assertWeatherDataV2(data);
944
+ if (this.cache) {
945
+ await this.cache.set(cacheKey, data);
946
+ if (!cacheKey.startsWith("id:")) await this.cache.set(this.buildBaseCacheKey(`id:${data.id}`, opts), data);
947
+ }
948
+ return data;
949
+ }
902
950
  };
951
+
952
+ //#endregion
953
+ export { CountryCodeList, CountryCodeSchema, OpenWeatherV2, assertWeatherDataV2, fetchErrorWrapper, getWeatherV2Description, iconSchema, isWeatherDataV2, langCodeSchema, langCodes, weatherDataV2Schema, weatherIdGroup, weatherIdSchema };
903
954
  //# sourceMappingURL=index.mjs.map