Malek | e6c3c72 | 2018-10-16 16:44:41 +0300 | [diff] [blame] | 1 | /* |
| 2 | * Copyright © 2018 European Support Limited |
| 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 | * http: //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 | import axios from 'axios'; |
| 18 | |
| 19 | let prevLastScanned; |
| 20 | let updateNotificationsTimeout; |
| 21 | let config; |
| 22 | let notificationsWorkerUpdateMillisecond; |
| 23 | |
| 24 | function updateNotifications() { |
| 25 | axios(config) |
| 26 | .then(response => { |
| 27 | const notifications = response.data; |
| 28 | |
| 29 | let lastScanned = notifications.lastScanned; |
| 30 | if (prevLastScanned !== lastScanned) { |
| 31 | postMessage(notifications); |
| 32 | } |
| 33 | prevLastScanned = lastScanned; |
| 34 | }) |
| 35 | .catch(() => {}); |
| 36 | |
| 37 | updateNotificationsTimeout = setTimeout( |
| 38 | updateNotifications, |
| 39 | notificationsWorkerUpdateMillisecond |
| 40 | ); |
| 41 | } |
| 42 | |
| 43 | navigator.connection.onchange = () => { |
| 44 | clearTimeout(updateNotificationsTimeout); |
| 45 | |
| 46 | if (navigator.onLine && config && notificationsWorkerUpdateMillisecond) { |
| 47 | updateNotifications(); |
| 48 | } |
| 49 | }; |
| 50 | |
| 51 | onmessage = ({ data }) => { |
| 52 | if (data && data.config && data.notificationsWorkerUpdateMillisecond) { |
| 53 | config = data.config; |
| 54 | notificationsWorkerUpdateMillisecond = |
| 55 | data.notificationsWorkerUpdateMillisecond; |
| 56 | |
| 57 | updateNotifications(); |
| 58 | } |
| 59 | }; |