├── .env ├── .gitignore ├── .glitch-assets ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── Your-First-PWA-Codelab.code-workspace ├── package.json ├── public ├── images │ ├── add.svg │ ├── clear-day.svg │ ├── clear-night.svg │ ├── cloudy.svg │ ├── favicon.ico │ ├── fog.svg │ ├── hail.svg │ ├── icons │ │ ├── icon-128x128.png │ │ ├── icon-144x144.png │ │ ├── icon-152x152.png │ │ ├── icon-192x192.png │ │ ├── icon-256x256.png │ │ ├── icon-32x32.png │ │ └── icon-512x512.png │ ├── install.svg │ ├── partly-cloudy-day.svg │ ├── partly-cloudy-night.svg │ ├── rain.svg │ ├── refresh.svg │ ├── sleet.svg │ ├── snow.svg │ ├── thunderstorm.svg │ ├── tornado.svg │ └── wind.svg ├── index.html ├── offline.html ├── scripts │ ├── app.js │ ├── install.js │ └── luxon-1.11.4.js ├── service-worker.js └── styles │ └── inline.css ├── server.js └── watch.json /.env: -------------------------------------------------------------------------------- 1 | # Environment Config 2 | # Store secrets and config variables in here, only invited 3 | # collaborators will be able to see your .env values 4 | # reference these in your code with process.env.SECRET_NAME 5 | 6 | DARKSKY_API_KEY="_PUT_YOUR_DARK_SKY_API_KEY_HERE_" 7 | 8 | # note: .env is a shell file so there can't be spaces around = 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | .DS_Store 3 | node_modules 4 | package-lock.json 5 | -------------------------------------------------------------------------------- /.glitch-assets: -------------------------------------------------------------------------------- 1 | {"name":"drag-in-files.svg","date":"2016-10-22T16:17:49.954Z","url":"https://cdn.hyperdev.com/drag-in-files.svg","type":"image/svg","size":7646,"imageWidth":276,"imageHeight":276,"thumbnail":"https://cdn.hyperdev.com/drag-in-files.svg","thumbnailWidth":276,"thumbnailHeight":276,"dominantColor":"rgb(102, 153, 205)","uuid":"adSBq97hhhpFNUna"} 2 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement. You (or your employer) retain the copyright to your contribution, 10 | this simply gives us permission to use and redistribute your contributions as 11 | part of the project. Head over to to see 12 | your current agreements on file or to sign a new one. 13 | 14 | You generally only need to submit a CLA once, so if you've already submitted one 15 | (even if it was for a different project), you probably don't need to do it 16 | again. 17 | 18 | ## Code reviews 19 | 20 | All submissions, including submissions by project members, require review. We 21 | use GitHub pull requests for this purpose. Consult 22 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 23 | information on using pull requests. 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Your First Progressive Web App Codelab 2 | 3 | These are the resource files needed for the 4 | [Your First Progressive Web App][codelab] codelab. 5 | 6 | In this codelab, you'll build a weather web app using Progressive Web App 7 | techniques. Your app will: 8 | 9 | * Use responsive design, so it works on desktop or mobile. 10 | * Be fast & reliable, using a service worker to precache the app resources 11 | (HTML, CSS, JavaScript, images) needed to run, and cache the weather data 12 | at runtime to improve performance. 13 | * Be installable, using a web app manifest and the `beforeinstallprompt` event 14 | to notify the user it's installable. 15 | 16 | 17 | ## What you'll learn 18 | 19 | * How to create and add a web app manifest 20 | * How to provide a simple offline experience 21 | * How to provide a full offline experience 22 | * How to make your app installable 23 | 24 | ## Getting started 25 | 26 | To get started, check out the [codelab instruction][codelab] 27 | 28 | 29 | ## Feedback 30 | 31 | This is a work in progress, if you find a mistake, please [file an issue][git-issue]. 32 | 33 | 34 | ## License 35 | 36 | Copyright 2019 Google, Inc. 37 | 38 | Licensed to the Apache Software Foundation (ASF) under one or more contributor 39 | license agreements. See the NOTICE file distributed with this work for 40 | additional information regarding copyright ownership. The ASF licenses this 41 | file to you under the Apache License, Version 2.0 (the “License”); you may not 42 | use this file except in compliance with the License. You may obtain a copy of 43 | the License at 44 | 45 | http://www.apache.org/licenses/LICENSE-2.0 46 | 47 | Unless required by applicable law or agreed to in writing, software distributed 48 | under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR 49 | CONDITIONS OF ANY KIND, either express or implied. See the License for the 50 | specific language governing permissions and limitations under the License. 51 | 52 | 53 | [codelab]: https://codelabs.developers.google.com/codelabs/your-first-pwapp/ 54 | [git-issue]: https://github.com/googlecodelabs/your-first-pwapp/issues 55 | -------------------------------------------------------------------------------- /Your-First-PWA-Codelab.code-workspace: -------------------------------------------------------------------------------- 1 | { 2 | "folders": [ 3 | { 4 | "name": "Your First PWA Codelab", 5 | "path": "." 6 | } 7 | ] 8 | } 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "your-first-pwapp", 3 | "version": "2.0.0", 4 | "description": "Codelab for Your First PWAPP", 5 | "homepage": "https://codelabs.developers.google.com/codelabs/your-first-pwapp/", 6 | "main": "server.js", 7 | "scripts": { 8 | "start": "node server.js" 9 | }, 10 | "dependencies": { 11 | "express": "^4.16.4", 12 | "express-http-to-https": "^1.1.4", 13 | "node-fetch": "^2.3.0" 14 | }, 15 | "engines": { 16 | "node": "8.x" 17 | }, 18 | "repository": { 19 | "type": "git", 20 | "url": "https://github.com/googlecodelabs/your-first-pwapp.git" 21 | }, 22 | "bugs": { 23 | "url": "https://github.com/googlecodelabs/your-first-pwapp/issues" 24 | }, 25 | "license": "Apache2", 26 | "keywords": [ 27 | "progressive-web-app", 28 | "pwa", 29 | "installable web app" 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /public/images/add.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/images/clear-day.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/images/clear-night.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/images/cloudy.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/images/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googlecodelabs/your-first-pwapp/44a973b551cf748faa7a7caeeaadcb9f4097983f/public/images/favicon.ico -------------------------------------------------------------------------------- /public/images/fog.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/images/hail.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/images/icons/icon-128x128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googlecodelabs/your-first-pwapp/44a973b551cf748faa7a7caeeaadcb9f4097983f/public/images/icons/icon-128x128.png -------------------------------------------------------------------------------- /public/images/icons/icon-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googlecodelabs/your-first-pwapp/44a973b551cf748faa7a7caeeaadcb9f4097983f/public/images/icons/icon-144x144.png -------------------------------------------------------------------------------- /public/images/icons/icon-152x152.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googlecodelabs/your-first-pwapp/44a973b551cf748faa7a7caeeaadcb9f4097983f/public/images/icons/icon-152x152.png -------------------------------------------------------------------------------- /public/images/icons/icon-192x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googlecodelabs/your-first-pwapp/44a973b551cf748faa7a7caeeaadcb9f4097983f/public/images/icons/icon-192x192.png -------------------------------------------------------------------------------- /public/images/icons/icon-256x256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googlecodelabs/your-first-pwapp/44a973b551cf748faa7a7caeeaadcb9f4097983f/public/images/icons/icon-256x256.png -------------------------------------------------------------------------------- /public/images/icons/icon-32x32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googlecodelabs/your-first-pwapp/44a973b551cf748faa7a7caeeaadcb9f4097983f/public/images/icons/icon-32x32.png -------------------------------------------------------------------------------- /public/images/icons/icon-512x512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/googlecodelabs/your-first-pwapp/44a973b551cf748faa7a7caeeaadcb9f4097983f/public/images/icons/icon-512x512.png -------------------------------------------------------------------------------- /public/images/install.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/images/partly-cloudy-day.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/images/partly-cloudy-night.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/images/rain.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/images/refresh.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/images/sleet.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/images/snow.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/images/thunderstorm.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/images/tornado.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/images/wind.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | Weather PWA 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 |
39 |

40 | Weather PWA 41 | 42 | Powered by Dark Sky 43 | 44 |

45 | 46 | 47 |
48 | 49 |
50 | 51 | 54 | 55 |
56 | Your First Progressive Web App Codelab
57 | Get started at https://g.co/codelabs/pwa. 58 |
59 | 60 | 173 |
174 | 175 |
176 |
177 |
Add new city
178 |
179 | 194 |
195 |
196 | 197 | 198 |
199 |
200 |
201 | 202 | 203 | 204 | 205 | 208 | 209 | 210 | 211 | -------------------------------------------------------------------------------- /public/offline.html: -------------------------------------------------------------------------------- 1 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | Weather PWA 26 | 27 | 28 | 29 | 127 | 128 | 129 |
130 |

131 | Weather PWA 132 | 133 | Powered by Dark Sky 134 | 135 |

136 |
137 |
138 |
139 | 140 |
141 | Oops, you appear to be offline, this app requires an internet 142 | connection. 143 |
144 |
145 |
146 | 147 | 148 | -------------------------------------------------------------------------------- /public/scripts/app.js: -------------------------------------------------------------------------------- 1 | /* 2 | * @license 3 | * Your First PWA Codelab (https://g.co/codelabs/pwa) 4 | * Copyright 2019 Google Inc. All rights reserved. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * https://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License 17 | */ 18 | 'use strict'; 19 | 20 | const weatherApp = { 21 | selectedLocations: {}, 22 | addDialogContainer: document.getElementById('addDialogContainer'), 23 | }; 24 | 25 | /** 26 | * Toggles the visibility of the add location dialog box. 27 | */ 28 | function toggleAddDialog() { 29 | weatherApp.addDialogContainer.classList.toggle('visible'); 30 | } 31 | 32 | /** 33 | * Event handler for butDialogAdd, adds the selected location to the list. 34 | */ 35 | function addLocation() { 36 | // Hide the dialog 37 | toggleAddDialog(); 38 | // Get the selected city 39 | const select = document.getElementById('selectCityToAdd'); 40 | const selected = select.options[select.selectedIndex]; 41 | const geo = selected.value; 42 | const label = selected.textContent; 43 | const location = {label: label, geo: geo}; 44 | // Create a new card & get the weather data from the server 45 | const card = getForecastCard(location); 46 | getForecastFromNetwork(geo).then((forecast) => { 47 | renderForecast(card, forecast); 48 | }); 49 | // Save the updated list of selected cities. 50 | weatherApp.selectedLocations[geo] = location; 51 | saveLocationList(weatherApp.selectedLocations); 52 | } 53 | 54 | /** 55 | * Event handler for .remove-city, removes a location from the list. 56 | * 57 | * @param {Event} evt 58 | */ 59 | function removeLocation(evt) { 60 | const parent = evt.srcElement.parentElement; 61 | parent.remove(); 62 | if (weatherApp.selectedLocations[parent.id]) { 63 | delete weatherApp.selectedLocations[parent.id]; 64 | saveLocationList(weatherApp.selectedLocations); 65 | } 66 | } 67 | 68 | /** 69 | * Renders the forecast data into the card element. 70 | * 71 | * @param {Element} card The card element to update. 72 | * @param {Object} data Weather forecast data to update the element with. 73 | */ 74 | function renderForecast(card, data) { 75 | if (!data) { 76 | // There's no data, skip the update. 77 | return; 78 | } 79 | 80 | // Find out when the element was last updated. 81 | const cardLastUpdatedElem = card.querySelector('.card-last-updated'); 82 | const cardLastUpdated = cardLastUpdatedElem.textContent; 83 | const lastUpdated = parseInt(cardLastUpdated); 84 | 85 | // If the data on the element is newer, skip the update. 86 | if (lastUpdated >= data.currently.time) { 87 | return; 88 | } 89 | cardLastUpdatedElem.textContent = data.currently.time; 90 | 91 | // Render the forecast data into the card. 92 | card.querySelector('.description').textContent = data.currently.summary; 93 | const forecastFrom = luxon.DateTime 94 | .fromSeconds(data.currently.time) 95 | .setZone(data.timezone) 96 | .toFormat('DDDD t'); 97 | card.querySelector('.date').textContent = forecastFrom; 98 | card.querySelector('.current .icon') 99 | .className = `icon ${data.currently.icon}`; 100 | card.querySelector('.current .temperature .value') 101 | .textContent = Math.round(data.currently.temperature); 102 | card.querySelector('.current .humidity .value') 103 | .textContent = Math.round(data.currently.humidity * 100); 104 | card.querySelector('.current .wind .value') 105 | .textContent = Math.round(data.currently.windSpeed); 106 | card.querySelector('.current .wind .direction') 107 | .textContent = Math.round(data.currently.windBearing); 108 | const sunrise = luxon.DateTime 109 | .fromSeconds(data.daily.data[0].sunriseTime) 110 | .setZone(data.timezone) 111 | .toFormat('t'); 112 | card.querySelector('.current .sunrise .value').textContent = sunrise; 113 | const sunset = luxon.DateTime 114 | .fromSeconds(data.daily.data[0].sunsetTime) 115 | .setZone(data.timezone) 116 | .toFormat('t'); 117 | card.querySelector('.current .sunset .value').textContent = sunset; 118 | 119 | // Render the next 7 days. 120 | const futureTiles = card.querySelectorAll('.future .oneday'); 121 | futureTiles.forEach((tile, index) => { 122 | const forecast = data.daily.data[index + 1]; 123 | const forecastFor = luxon.DateTime 124 | .fromSeconds(forecast.time) 125 | .setZone(data.timezone) 126 | .toFormat('ccc'); 127 | tile.querySelector('.date').textContent = forecastFor; 128 | tile.querySelector('.icon').className = `icon ${forecast.icon}`; 129 | tile.querySelector('.temp-high .value') 130 | .textContent = Math.round(forecast.temperatureHigh); 131 | tile.querySelector('.temp-low .value') 132 | .textContent = Math.round(forecast.temperatureLow); 133 | }); 134 | 135 | // If the loading spinner is still visible, remove it. 136 | const spinner = card.querySelector('.card-spinner'); 137 | if (spinner) { 138 | card.removeChild(spinner); 139 | } 140 | } 141 | 142 | /** 143 | * Get's the latest forecast data from the network. 144 | * 145 | * @param {string} coords Location object to. 146 | * @return {Object} The weather forecast, if the request fails, return null. 147 | */ 148 | function getForecastFromNetwork(coords) { 149 | return fetch(`/forecast/${coords}`) 150 | .then((response) => { 151 | return response.json(); 152 | }) 153 | .catch(() => { 154 | return null; 155 | }); 156 | } 157 | 158 | /** 159 | * Get's the cached forecast data from the caches object. 160 | * 161 | * @param {string} coords Location object to. 162 | * @return {Object} The weather forecast, if the request fails, return null. 163 | */ 164 | function getForecastFromCache(coords) { 165 | // CODELAB: Add code to get weather forecast from the caches object. 166 | 167 | } 168 | 169 | /** 170 | * Get's the HTML element for the weather forecast, or clones the template 171 | * and adds it to the DOM if we're adding a new item. 172 | * 173 | * @param {Object} location Location object 174 | * @return {Element} The element for the weather forecast. 175 | */ 176 | function getForecastCard(location) { 177 | const id = location.geo; 178 | const card = document.getElementById(id); 179 | if (card) { 180 | return card; 181 | } 182 | const newCard = document.getElementById('weather-template').cloneNode(true); 183 | newCard.querySelector('.location').textContent = location.label; 184 | newCard.setAttribute('id', id); 185 | newCard.querySelector('.remove-city') 186 | .addEventListener('click', removeLocation); 187 | document.querySelector('main').appendChild(newCard); 188 | newCard.removeAttribute('hidden'); 189 | return newCard; 190 | } 191 | 192 | /** 193 | * Gets the latest weather forecast data and updates each card with the 194 | * new data. 195 | */ 196 | function updateData() { 197 | Object.keys(weatherApp.selectedLocations).forEach((key) => { 198 | const location = weatherApp.selectedLocations[key]; 199 | const card = getForecastCard(location); 200 | // CODELAB: Add code to call getForecastFromCache 201 | 202 | // Get the forecast data from the network. 203 | getForecastFromNetwork(location.geo) 204 | .then((forecast) => { 205 | renderForecast(card, forecast); 206 | }); 207 | }); 208 | } 209 | 210 | /** 211 | * Saves the list of locations. 212 | * 213 | * @param {Object} locations The list of locations to save. 214 | */ 215 | function saveLocationList(locations) { 216 | const data = JSON.stringify(locations); 217 | localStorage.setItem('locationList', data); 218 | } 219 | 220 | /** 221 | * Loads the list of saved location. 222 | * 223 | * @return {Array} 224 | */ 225 | function loadLocationList() { 226 | let locations = localStorage.getItem('locationList'); 227 | if (locations) { 228 | try { 229 | locations = JSON.parse(locations); 230 | } catch (ex) { 231 | locations = {}; 232 | } 233 | } 234 | if (!locations || Object.keys(locations).length === 0) { 235 | const key = '40.7720232,-73.9732319'; 236 | locations = {}; 237 | locations[key] = {label: 'New York City', geo: '40.7720232,-73.9732319'}; 238 | } 239 | return locations; 240 | } 241 | 242 | /** 243 | * Initialize the app, gets the list of locations from local storage, then 244 | * renders the initial data. 245 | */ 246 | function init() { 247 | // Get the location list, and update the UI. 248 | weatherApp.selectedLocations = loadLocationList(); 249 | updateData(); 250 | 251 | // Set up the event handlers for all of the buttons. 252 | document.getElementById('butRefresh').addEventListener('click', updateData); 253 | document.getElementById('butAdd').addEventListener('click', toggleAddDialog); 254 | document.getElementById('butDialogCancel') 255 | .addEventListener('click', toggleAddDialog); 256 | document.getElementById('butDialogAdd') 257 | .addEventListener('click', addLocation); 258 | } 259 | 260 | init(); 261 | -------------------------------------------------------------------------------- /public/scripts/install.js: -------------------------------------------------------------------------------- 1 | /* 2 | * @license 3 | * Your First PWA Codelab (https://g.co/codelabs/pwa) 4 | * Copyright 2019 Google Inc. All rights reserved. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * https://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License 17 | */ 18 | 'use strict'; 19 | 20 | let deferredInstallPrompt = null; 21 | const installButton = document.getElementById('butInstall'); 22 | installButton.addEventListener('click', installPWA); 23 | 24 | // CODELAB: Add event listener for beforeinstallprompt event 25 | 26 | 27 | /** 28 | * Event handler for beforeinstallprompt event. 29 | * Saves the event & shows install button. 30 | * 31 | * @param {Event} evt 32 | */ 33 | function saveBeforeInstallPromptEvent(evt) { 34 | // CODELAB: Add code to save event & show the install button. 35 | 36 | } 37 | 38 | 39 | /** 40 | * Event handler for butInstall - Does the PWA installation. 41 | * 42 | * @param {Event} evt 43 | */ 44 | function installPWA(evt) { 45 | // CODELAB: Add code show install prompt & hide the install button. 46 | 47 | // CODELAB: Log user response to prompt. 48 | 49 | } 50 | 51 | // CODELAB: Add event listener for appinstalled event 52 | 53 | /** 54 | * Event handler for appinstalled event. 55 | * Log the installation to analytics or save the event somehow. 56 | * 57 | * @param {Event} evt 58 | */ 59 | function logAppInstalled(evt) { 60 | // CODELAB: Add code to log the event 61 | 62 | } 63 | -------------------------------------------------------------------------------- /public/service-worker.js: -------------------------------------------------------------------------------- 1 | /* 2 | * @license 3 | * Your First PWA Codelab (https://g.co/codelabs/pwa) 4 | * Copyright 2019 Google Inc. All rights reserved. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * https://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License 17 | */ 18 | 'use strict'; 19 | 20 | // CODELAB: Update cache names any time any of the cached files change. 21 | const CACHE_NAME = 'static-cache-v1'; 22 | 23 | // CODELAB: Add list of files to cache here. 24 | const FILES_TO_CACHE = [ 25 | ]; 26 | 27 | self.addEventListener('install', (evt) => { 28 | console.log('[ServiceWorker] Install'); 29 | // CODELAB: Precache static resources here. 30 | 31 | self.skipWaiting(); 32 | }); 33 | 34 | self.addEventListener('activate', (evt) => { 35 | console.log('[ServiceWorker] Activate'); 36 | // CODELAB: Remove previous cached data from disk. 37 | 38 | self.clients.claim(); 39 | }); 40 | 41 | self.addEventListener('fetch', (evt) => { 42 | console.log('[ServiceWorker] Fetch', evt.request.url); 43 | // CODELAB: Add fetch event handler here. 44 | 45 | }); 46 | -------------------------------------------------------------------------------- /public/styles/inline.css: -------------------------------------------------------------------------------- 1 | /* 2 | * @license 3 | * Your First PWA Codelab (https://g.co/codelabs/pwa) 4 | * Copyright 2019 Google Inc. All rights reserved. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * https://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License 17 | */ 18 | 19 | * { 20 | box-sizing: border-box; 21 | } 22 | 23 | html, 24 | body { 25 | color: #444; 26 | font-family: 'Helvetica', 'Verdana', sans-serif; 27 | -moz-osx-font-smoothing: grayscale; 28 | -webkit-font-smoothing: antialiased; 29 | height: 100%; 30 | margin: 0; 31 | padding: 0; 32 | width: 100%; 33 | } 34 | 35 | html { 36 | overflow: hidden; 37 | } 38 | 39 | body { 40 | align-content: stretch; 41 | align-items: stretch; 42 | background: #ececec; 43 | display: flex; 44 | flex-direction: column; 45 | flex-wrap: nowrap; 46 | justify-content: flex-start; 47 | } 48 | 49 | /** 50 | * Header 51 | */ 52 | 53 | .header { 54 | align-content: center; 55 | align-items: stretch; 56 | background: #3f51b5; 57 | box-shadow: 58 | 0 4px 5px 0 rgba(0, 0, 0, 0.14), 59 | 0 2px 9px 1px rgba(0, 0, 0, 0.12), 60 | 0 4px 2px -2px rgba(0, 0, 0, 0.2); 61 | color: #fff; 62 | display: flex; 63 | flex-direction: row; 64 | flex-wrap: nowrap; 65 | font-size: 20px; 66 | height: 56px; 67 | justify-content: flex-start; 68 | padding: 16px 16px 0 16px; 69 | position: fixed; 70 | transition: transform 0.233s cubic-bezier(0, 0, 0.21, 1) 0.1s; 71 | width: 100%; 72 | will-change: transform; 73 | z-index: 1000; 74 | } 75 | 76 | .header h1 { 77 | flex: 1; 78 | font-size: 20px; 79 | font-weight: 400; 80 | margin: 0; 81 | } 82 | 83 | .header button { 84 | border: none; 85 | cursor: pointer; 86 | height: 24px; 87 | margin-right: 16px; 88 | opacity: 0.54; 89 | outline: none; 90 | overflow: hidden; 91 | text-indent: -30000px; 92 | transition: opacity 0.333s cubic-bezier(0, 0, 0.21, 1); 93 | width: 24px; 94 | } 95 | 96 | .header #butRefresh { 97 | background: url(/images/refresh.svg) center center no-repeat; 98 | } 99 | 100 | .header #butInstall { 101 | background: url(/images/install.svg) center center no-repeat; 102 | } 103 | 104 | .header .powered-by { 105 | color: white; 106 | font-size: 0.6em; 107 | text-decoration: none; 108 | } 109 | 110 | /** 111 | * Loading spinner 112 | */ 113 | 114 | .card-spinner { 115 | background-color: rgba(255, 255, 255, 0.8); 116 | height: 100%; 117 | margin-left: -16px; 118 | margin-top: -16px; 119 | position: absolute; 120 | width: 100%; 121 | } 122 | 123 | .card-spinner svg { 124 | left: 50%; 125 | position: absolute; 126 | top: 50%; 127 | transform: translate(-50%, -50%); 128 | } 129 | 130 | .card-spinner svg circle { 131 | animation: line 1.6s cubic-bezier(0.4, 0, 0.2, 1) infinite, rotate 1.6s linear infinite; 132 | box-sizing: border-box; 133 | stroke: #3f51b5; 134 | stroke-width: 3px; 135 | transform-origin: 50%; 136 | } 137 | 138 | @keyframes rotate { 139 | from { transform: rotate(0); } 140 | to { transform: rotate(450deg); } 141 | } 142 | 143 | @keyframes line { 144 | 0% { 145 | stroke-dasharray: 2, 85.964; 146 | transform: rotate(0); 147 | } 148 | 149 | 50% { 150 | stroke-dasharray: 65.973, 21.9911; 151 | stroke-dashoffset: 0; 152 | } 153 | 154 | 100% { 155 | stroke-dasharray: 2, 85.964; 156 | stroke-dashoffset: -65.973; 157 | transform: rotate(90deg); 158 | } 159 | } 160 | 161 | /** 162 | * Icons 163 | */ 164 | 165 | .icon { 166 | background-repeat: no-repeat; 167 | background-size: contain; 168 | } 169 | 170 | .icon.add { 171 | background-image: url("/images/add.svg"); 172 | } 173 | 174 | .icon.clear-day { 175 | background-image: url("/images/clear-day.svg"); 176 | } 177 | 178 | .icon.clear-night { 179 | background-image: url("/images/clear-night.svg"); 180 | } 181 | 182 | .icon.rain { 183 | background-image: url("/images/rain.svg"); 184 | } 185 | 186 | .icon.snow { 187 | background-image: url("/images/snow.svg"); 188 | } 189 | 190 | .icon.sleet { 191 | background-image: url("/images/sleet.svg"); 192 | } 193 | 194 | .icon.wind { 195 | background-image: url("/images/wind.svg"); 196 | } 197 | 198 | .icon.fog { 199 | background-image: url("/images/fog.svg"); 200 | } 201 | 202 | .icon.cloudy { 203 | background-image: url("/images/cloudy.svg"); 204 | } 205 | 206 | .icon.partly-cloudy-day { 207 | background-image: url("/images/partly-cloudy-day.svg"); 208 | } 209 | 210 | .icon.partly-cloudy-night { 211 | background-image: url("/images/partly-cloudy-night.svg"); 212 | } 213 | 214 | .icon.hail { 215 | background-image: url("/images/hail.svg"); 216 | } 217 | 218 | .icon.thunderstorm { 219 | background-image: url("/images/thunderstorm.svg"); 220 | } 221 | 222 | .icon.tornado { 223 | background-image: url("/images/tornado.svg"); 224 | } 225 | 226 | /** 227 | * Main body 228 | */ 229 | 230 | .main { 231 | flex: 1; 232 | overflow-x: hidden; 233 | overflow-y: auto; 234 | padding-top: 60px; 235 | } 236 | 237 | .main .fab { 238 | background-color: #3f51b5; 239 | border-radius: 50%; 240 | bottom: 1rem; 241 | height: 56px; 242 | padding: 12px; 243 | position: fixed; 244 | right: 1rem; 245 | width: 56px; 246 | z-index: 1000; 247 | } 248 | 249 | .main .fab .icon { 250 | display: inline-block; 251 | height: 100%; 252 | width: 100%; 253 | } 254 | 255 | /** 256 | * Add dialog 257 | */ 258 | 259 | #addDialogContainer { 260 | background: rgba(0, 0, 0, 0.57); 261 | height: 100%; 262 | left: 0; 263 | opacity: 0; 264 | pointer-events: none; 265 | position: fixed; 266 | top: 0; 267 | transition: opacity 0.333s cubic-bezier(0, 0, 0.21, 1); 268 | width: 100%; 269 | will-change: opacity; 270 | } 271 | 272 | #addDialogContainer.visible { 273 | opacity: 1; 274 | pointer-events: auto; 275 | } 276 | 277 | .dialog { 278 | background: #fff; 279 | border-radius: 2px; 280 | box-shadow: 281 | 0 0 14px rgba(0, 0, 0, 0.24), 282 | 0 14px 28px rgba(0, 0, 0, 0.48); 283 | left: 50%; 284 | min-width: 280px; 285 | position: absolute; 286 | top: 50%; 287 | transform: translate(-50%, -50%) translateY(30px); 288 | transition: transform 0.333s cubic-bezier(0, 0, 0.21, 1) 0.05s; 289 | } 290 | 291 | .dialog > div { 292 | padding-left: 24px; 293 | padding-right: 24px; 294 | } 295 | 296 | .dialog-title { 297 | font-size: 1.25em; 298 | padding-top: 20px; 299 | } 300 | 301 | .dialog-body { 302 | padding-bottom: 24px; 303 | padding-top: 20px; 304 | } 305 | 306 | .dialog-body select { 307 | width: 100%; 308 | } 309 | 310 | .dialog-buttons { 311 | float: right; 312 | padding-bottom: 16px; 313 | padding-right: 17px !important; 314 | } 315 | 316 | .dialog .button { 317 | background: transparent; 318 | border: none; 319 | font-size: 14px; 320 | text-transform: uppercase; 321 | } 322 | 323 | /** 324 | * Weather forecast card 325 | */ 326 | 327 | .weather-card { 328 | background: #fff; 329 | border-radius: 2px; 330 | box-shadow: 331 | 0 2px 2px 0 rgba(0, 0, 0, 0.14), 332 | 0 3px 1px -2px rgba(0, 0, 0, 0.2), 333 | 0 1px 5px 0 rgba(0, 0, 0, 0.12); 334 | box-sizing: border-box; 335 | margin: 16px; 336 | padding: 16px; 337 | position: relative; 338 | } 339 | 340 | .weather-card .remove-city { 341 | background-color: transparent; 342 | border: none; 343 | float: right; 344 | font-size: x-large; 345 | } 346 | 347 | .weather-card .location { 348 | font-size: 1.75em; 349 | } 350 | 351 | .weather-card .date, 352 | .weather-card .description { 353 | font-size: 1.25em; 354 | } 355 | 356 | .weather-card .current { 357 | display: flex; 358 | } 359 | 360 | .weather-card .current .icon { 361 | height: 128px; 362 | width: 128px; 363 | } 364 | 365 | .weather-card .current .visual { 366 | display: flex; 367 | font-size: 4em; 368 | } 369 | 370 | .weather-card .current .visual .scale { 371 | font-size: 0.5em; 372 | vertical-align: super; 373 | } 374 | 375 | .weather-card .current .visual, 376 | .weather-card .current .description { 377 | flex-grow: 1; 378 | } 379 | 380 | .weather-card .current .description .label { 381 | color: #666; 382 | } 383 | 384 | .weather-card .future { 385 | display: flex; 386 | } 387 | 388 | .weather-card .future .oneday { 389 | flex-grow: 1; 390 | text-align: center; 391 | } 392 | 393 | .weather-card .future .oneday .icon { 394 | height: 64px; 395 | margin-left: auto; 396 | margin-right: auto; 397 | width: 64px; 398 | } 399 | 400 | .weather-card .future .oneday .temp-high, 401 | .weather-card .future .oneday .temp-low { 402 | display: inline-block; 403 | } 404 | 405 | .weather-card .future .oneday .temp-low { 406 | color: #666; 407 | } 408 | 409 | /** 410 | * Media query to adjust size of content for small screens 411 | */ 412 | 413 | @media (max-width: 450px) { 414 | .weather-card .date, 415 | .weather-card .description { 416 | font-size: 0.9em; 417 | } 418 | 419 | .weather-card .current .icon { 420 | height: 96px; 421 | width: 96px; 422 | } 423 | 424 | .weather-card .current .visual { 425 | font-size: 3em; 426 | } 427 | 428 | .weather-card .future .oneday .icon { 429 | height: 32px; 430 | width: 32px; 431 | } 432 | } 433 | -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | /* eslint-env node */ 2 | /* 3 | * @license 4 | * Your First PWA Codelab (https://g.co/codelabs/pwa) 5 | * Copyright 2019 Google Inc. All rights reserved. 6 | * 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * https://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License 18 | */ 19 | 'use strict'; 20 | 21 | const express = require('express'); 22 | const fetch = require('node-fetch'); 23 | const redirectToHTTPS = require('express-http-to-https').redirectToHTTPS; 24 | 25 | // CODELAB: Change this to add a delay (ms) before the server responds. 26 | const FORECAST_DELAY = 0; 27 | 28 | // CODELAB: If running locally, set your Dark Sky API key here 29 | const API_KEY = process.env.DARKSKY_API_KEY; 30 | const BASE_URL = `https://api.darksky.net/forecast`; 31 | 32 | // Fake forecast data used if we can't reach the Dark Sky API 33 | const fakeForecast = { 34 | fakeData: true, 35 | latitude: 0, 36 | longitude: 0, 37 | timezone: 'America/New_York', 38 | currently: { 39 | time: 0, 40 | summary: 'Clear', 41 | icon: 'clear-day', 42 | temperature: 43.4, 43 | humidity: 0.62, 44 | windSpeed: 3.74, 45 | windBearing: 208, 46 | }, 47 | daily: { 48 | data: [ 49 | { 50 | time: 0, 51 | icon: 'partly-cloudy-night', 52 | sunriseTime: 1553079633, 53 | sunsetTime: 1553123320, 54 | temperatureHigh: 52.91, 55 | temperatureLow: 41.35, 56 | }, 57 | { 58 | time: 86400, 59 | icon: 'rain', 60 | sunriseTime: 1553165933, 61 | sunsetTime: 1553209784, 62 | temperatureHigh: 48.01, 63 | temperatureLow: 44.17, 64 | }, 65 | { 66 | time: 172800, 67 | icon: 'rain', 68 | sunriseTime: 1553252232, 69 | sunsetTime: 1553296247, 70 | temperatureHigh: 50.31, 71 | temperatureLow: 33.61, 72 | }, 73 | { 74 | time: 259200, 75 | icon: 'partly-cloudy-night', 76 | sunriseTime: 1553338532, 77 | sunsetTime: 1553382710, 78 | temperatureHigh: 46.44, 79 | temperatureLow: 33.82, 80 | }, 81 | { 82 | time: 345600, 83 | icon: 'partly-cloudy-night', 84 | sunriseTime: 1553424831, 85 | sunsetTime: 1553469172, 86 | temperatureHigh: 60.5, 87 | temperatureLow: 43.82, 88 | }, 89 | { 90 | time: 432000, 91 | icon: 'rain', 92 | sunriseTime: 1553511130, 93 | sunsetTime: 1553555635, 94 | temperatureHigh: 61.79, 95 | temperatureLow: 32.8, 96 | }, 97 | { 98 | time: 518400, 99 | icon: 'rain', 100 | sunriseTime: 1553597430, 101 | sunsetTime: 1553642098, 102 | temperatureHigh: 48.28, 103 | temperatureLow: 33.49, 104 | }, 105 | { 106 | time: 604800, 107 | icon: 'snow', 108 | sunriseTime: 1553683730, 109 | sunsetTime: 1553728560, 110 | temperatureHigh: 43.58, 111 | temperatureLow: 33.68, 112 | }, 113 | ], 114 | }, 115 | }; 116 | 117 | /** 118 | * Generates a fake forecast in case the weather API is not available. 119 | * 120 | * @param {String} location GPS location to use. 121 | * @return {Object} forecast object. 122 | */ 123 | function generateFakeForecast(location) { 124 | location = location || '40.7720232,-73.9732319'; 125 | const commaAt = location.indexOf(','); 126 | 127 | // Create a new copy of the forecast 128 | const result = Object.assign({}, fakeForecast); 129 | result.latitude = parseFloat(location.substr(0, commaAt)); 130 | result.longitude = parseFloat(location.substr(commaAt + 1)); 131 | return result; 132 | } 133 | 134 | 135 | /** 136 | * Gets the weather forecast from the Dark Sky API for the given location. 137 | * 138 | * @param {Request} req request object from Express. 139 | * @param {Response} resp response object from Express. 140 | */ 141 | function getForecast(req, resp) { 142 | const location = req.params.location || '40.7720232,-73.9732319'; 143 | const url = `${BASE_URL}/${API_KEY}/${location}`; 144 | fetch(url).then((resp) => { 145 | if (resp.status !== 200) { 146 | throw new Error(resp.statusText); 147 | } 148 | return resp.json(); 149 | }).then((data) => { 150 | setTimeout(() => { 151 | resp.json(data); 152 | }, FORECAST_DELAY); 153 | }).catch((err) => { 154 | console.error('Dark Sky API Error:', err.message); 155 | resp.json(generateFakeForecast(location)); 156 | }); 157 | } 158 | 159 | /** 160 | * Starts the Express server. 161 | * 162 | * @return {ExpressServer} instance of the Express server. 163 | */ 164 | function startServer() { 165 | const app = express(); 166 | 167 | // Redirect HTTP to HTTPS, 168 | app.use(redirectToHTTPS([/localhost:(\d{4})/], [], 301)); 169 | 170 | // Logging for each request 171 | app.use((req, resp, next) => { 172 | const now = new Date(); 173 | const time = `${now.toLocaleDateString()} - ${now.toLocaleTimeString()}`; 174 | const path = `"${req.method} ${req.path}"`; 175 | const m = `${req.ip} - ${time} - ${path}`; 176 | // eslint-disable-next-line no-console 177 | console.log(m); 178 | next(); 179 | }); 180 | 181 | // Handle requests for the data 182 | app.get('/forecast/:location', getForecast); 183 | app.get('/forecast/', getForecast); 184 | app.get('/forecast', getForecast); 185 | 186 | // Handle requests for static files 187 | app.use(express.static('public')); 188 | 189 | // Start the server 190 | return app.listen('8000', () => { 191 | // eslint-disable-next-line no-console 192 | console.log('Local DevServer Started on port 8000...'); 193 | }); 194 | } 195 | 196 | startServer(); 197 | -------------------------------------------------------------------------------- /watch.json: -------------------------------------------------------------------------------- 1 | { 2 | "install": { 3 | "include": [ 4 | "^package\\.json$", 5 | "^\\.env$" 6 | ] 7 | }, 8 | "restart": { 9 | "exclude": [ 10 | "^public/" 11 | ], 12 | "include": [ 13 | "^\\.env$", 14 | "\\.js$", 15 | "\\.json" 16 | ] 17 | }, 18 | "throttle": 500 19 | } 20 | --------------------------------------------------------------------------------