@mharj/openweathermap
Advanced tools
Comparing version 0.0.3 to 0.0.4
@@ -8,5 +8,22 @@ "use strict"; | ||
const fetchResult = (0, mharj_result_1.safeAsyncResultBuilder)(fetch); | ||
function isJson(response) { | ||
const contentType = response.headers.get('content-type'); | ||
return (contentType && contentType.startsWith('application/json')) || false; | ||
} | ||
function isOpenWeatherError(data) { | ||
return typeof data === 'object' && data !== null && 'cod' in data && 'message' in data; | ||
} | ||
const basePath = 'https://api.openweathermap.org/data/2.5/weather'; | ||
function buildUrl(params) { | ||
return `${basePath}?${params.toString()}`; | ||
} | ||
function buildLogUrl(params) { | ||
const logParams = new URLSearchParams(params); | ||
logParams.set('appid', '***'); | ||
return buildUrl(logParams); | ||
} | ||
const defaultImplementation = { | ||
dataWeatherApi: async (params) => { | ||
const result = await fetchResult(`https://api.openweathermap.org/data/2.5/weather?${params.toString()}`); | ||
const logUrl = buildLogUrl(params); | ||
const result = await fetchResult(buildUrl(params)); | ||
if (!result.isOk) { | ||
@@ -17,4 +34,13 @@ return (0, mharj_result_1.Err)(result.err()); | ||
if (!res.ok) { | ||
return (0, mharj_result_1.Err)(new TypeError(`OpenWeatherV2 http error: ${res.status} ${res.statusText}`)); | ||
if (isJson(res)) { | ||
const data = res.json(); | ||
if (isOpenWeatherError(data)) { | ||
return (0, mharj_result_1.Err)(new TypeError(`OpenWeatherV2 error: ${data.message} from ${logUrl}`)); | ||
} | ||
} | ||
return (0, mharj_result_1.Err)(new TypeError(`OpenWeatherV2 http error: ${res.status} ${res.statusText} from ${logUrl}`)); | ||
} | ||
if (!isJson(res)) { | ||
return (0, mharj_result_1.Err)(new TypeError(`OpenWeatherV2 response is not json payload from ${logUrl}`)); | ||
} | ||
const data = await (0, mharj_result_1.safeAsyncResult)(res.json()); | ||
@@ -21,0 +47,0 @@ (0, types_1.assertWeatherDataV2)(data); |
{ | ||
"name": "@mharj/openweathermap", | ||
"version": "0.0.3", | ||
"version": "0.0.4", | ||
"description": "Open Weather API Client", | ||
@@ -5,0 +5,0 @@ "main": "./dist/index.js", |
Sorry, the diff of this file is not supported yet
93339
1642