Last active
February 12, 2023 10:07
-
-
Save zmajstor/993f964e821aca032ce797d972f01b3c to your computer and use it in GitHub Desktop.
USD srednji_tecaj in Google Sheets via HNB API V3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Custom Functions in Google Sheets: | |
// https://developers.google.com/apps-script/guides/sheets/functions | |
// | |
function usdTecajNaDan(value) { | |
function formatDatum(value) { | |
switch (typeof value) { | |
case "string": | |
return value; | |
case "object": | |
// assuming it's a date object | |
let date = new Date(value); | |
// return only date part (without time) | |
return date.toISOString().substring(0, 10); | |
default: | |
throw Error(`invalid value type: ${typeof value}`); | |
} | |
} | |
const datumISO = formatDatum(value); | |
// check date format which HNB API V3 expect, e.g. 2023-02-12 | |
if (!datumISO.match(/^\d{4}-([0]\d|1[0-2])-([0-2]\d|3[01])$/g)) { | |
throw Error(`invalid ISO date format: ${datumISO}`); | |
} | |
const url = "https://api.hnb.hr/tecajn-eur/v3?valuta=USD&datum-primjene=" + datumISO; | |
const responseText = UrlFetchApp.fetch(url).getContentText(); | |
// Logger.log(responseText); | |
return JSON.parse(responseText)[0].srednji_tecaj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment