|
| 1 | +/** |
| 2 | + * Copyright 2022 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +// [START full-sample] |
| 18 | +// Dependencies for callable functions. |
| 19 | +const {onCall, HttpsError} = require("firebase-functions/v2/https"); |
| 20 | + |
| 21 | +/** |
| 22 | + * Gets the weather from the national weather service |
| 23 | + * https://www.weather.gov/documentation/services-web-api |
| 24 | + * |
| 25 | + * @param {number} lat |
| 26 | + * @param {number} lng |
| 27 | + */ |
| 28 | +async function weatherForecastApi(lat, lng) { |
| 29 | + const resp = await fetch(`https://api.weather.gov/points/${lat},${lng}`); |
| 30 | + |
| 31 | + if (!resp.ok) { |
| 32 | + return `error: ${resp.status}`; |
| 33 | + } |
| 34 | + |
| 35 | + const forecastUrl = (await resp.json()).properties.forecast; |
| 36 | + const forecastResp = await fetch(forecastUrl); |
| 37 | + |
| 38 | + if (!forecastResp.ok) { |
| 39 | + return `error: ${forecastResp.status}`; |
| 40 | + } |
| 41 | + |
| 42 | + // add an artificial wait to emphasize stream-iness |
| 43 | + await new Promise((resolve) => setTimeout(resolve, Math.random() * 1500)); |
| 44 | + |
| 45 | + return forecastResp.json(); |
| 46 | +} |
| 47 | + |
| 48 | +// [START streaming-callable] |
| 49 | +exports.getForecast = onCall(async (request, response) => { |
| 50 | + if (request.data?.locations?.length < 1) { |
| 51 | + throw new HttpsError("invalid-argument", "Missing locations to forecast"); |
| 52 | + } |
| 53 | + |
| 54 | + // fetch forecast data for all requested locations |
| 55 | + const allRequests = request.data.locations.map( |
| 56 | + async ({latitude, longitude}) => { |
| 57 | + const forecast = await weatherForecastApi(latitude, longitude); |
| 58 | + const result = {latitude, longitude, forecast}; |
| 59 | + |
| 60 | + // clients that support streaming will have each |
| 61 | + // forecast streamed to them as they complete |
| 62 | + if (request.acceptsStreaming) { |
| 63 | + response.sendChunk(result); |
| 64 | + } |
| 65 | + |
| 66 | + return result; |
| 67 | + }, |
| 68 | + ); |
| 69 | + |
| 70 | + // Return the full set of data to all clients |
| 71 | + return Promise.all(allRequests); |
| 72 | +}); |
| 73 | +// [END streaming-callable] |
| 74 | +// [END full-sample] |
0 commit comments