Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Start writing Firebase Functions
  2. // https://firebase.google.com/docs/functions/typescript
  3.  
  4. import * as admin from 'firebase-admin';
  5. import fetch from 'node-fetch';
  6. import * as functions from 'firebase-functions';
  7.  
  8.  
  9. //replace with MTA API URL and key
  10. const myUrl = "https://jsonplaceholder.typicode.com/posts/1";
  11.  
  12. var cachedMessage = {};
  13.  
  14. const makeHttpRequest = async (url:string) => {
  15.   try {
  16.     console.log('making http request');
  17.     const response = await fetch(url);
  18.     console.log("fetched  response:" + response);
  19.     const json = await response.json();
  20.     console.log("Formatted JSON:" + json);
  21.     return json;
  22.   } catch (error) {
  23.     console.log(error);
  24.   }
  25. };
  26.  
  27. console.log('Calling makeHttpRequest(url)');
  28. makeHttpRequest(myUrl);
  29. console.log('await statement is being ignored if this is logged before makeHttpRequest(url) is complete');
  30. admin.initializeApp();
  31.  
  32. //correct way to schedule cron instead of setInterval
  33. exports.scheduledFunction = functions.pubsub.schedule('every 2 minutes').onRun((context) => {
  34.     cachedMessage = makeHttpRequest(myUrl);
  35. });
  36.  
  37. //expose the response via endpoint
  38. export const requestEndpoint = functions.https.onRequest((request, response) => {
  39.     response.send(cachedMessage)
  40. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement