Sarah K
Sarah K

Reputation: 377

Getting json from an api in a google cloud pubsub scheduled function

I'm a tad frustrated because I could write this in a few minutes in PHP or dart or even vanilla javascript but I'm getting stuck in writing a function for Google Cloud.

I want to periodically call an API, take what I want from the json and save as a document. Sounds easy... but the API bit is tripping me up. I'm getting missing bracket errors in terminal.

Are either of these functions on the right track?

exports.updateWeather = functions.pubsub.schedule('0 */9 * * *').onRun((context) =>  {
    import axios from 'axios';

    let timezone = 'Pacific/Auckland';
    
     axios.get("https://www.timeapi.io/api/TimeZone/zone?" + timezone, {cache: no-cache}) 
    .then(response => response.json())
    .then(data => console.log(data));

    return null;
  });

  exports.fetchWeather = functions
  .https
  .onRequest((request, response) => {
//const location =request.body;
import axios from 'axios';

  return  axios.get('https://www.timeapi.io/api/TimeZone/zone?timeZone=Pacific/Auckland')
  .then(apiResponse => {
    return { 
      body: apiResponse.data
    }
  })
  .catch(error => {
    console.log(error);

  throw new functions.https.HttpsError('Time update error', error);
  });
  });

Upvotes: 0

Views: 133

Answers (1)

Sarah K
Sarah K

Reputation: 377

I've round in a few circles but here's what I have working. I'm open to feedback but just pleased to have it working!

    import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();

//import * as express from "express";
//import * as cors from "cors";
import axios, {AxiosResponse} from "axios";

const db = admin.firestore();

export const updateTimes = functions.https.onRequest((request, response) => {
  getTimeJson("Pacific/Auckland", 0);
  getTimeJson("Australia/Sydney", 1);
  return getTimeJson("Australia/Perth", 2);
});

function getTimeJson(timezone: String, city: Number) {
  let utid = timezone.replace("/", "");
  axios
    .get(`https://www.timeapi.io/api/TimeZone/zone?timeZone=${timezone}`)
    .then((resultData: AxiosResponse) => {
      const timeRef = db.doc(`usertimes/${utid}`);
      return timeRef.set({
        dateTime: resultData.data.currentLocalTime,
        utcoffset: resultData.data.currentUtcOffset.seconds,
        tz: timezone,
        city: city,
        daylightSaving: resultData.data.isDayLightSavingActive
      });
    });
}

Upvotes: 1

Related Questions