-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
228 lines (190 loc) · 8.48 KB
/
sw.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
importScripts("https://cdn.jsdelivr.net/npm/[email protected]/dist/pouchdb.min.js")
importScripts("./js/utils/sw-db.js")
const STATIC_CACHE = 'static-v1.0'
const DYNAMYC_CACHE = 'dynamic-v1.0'
const INMUTABLE_CACHE = 'inmutable-v1.0'
const clearCache = (cacheName, maxItemSize) => {
caches.open(cacheName).then((cache) => {
return cache.keys().then((items) => {
if (items.length >= maxItemSize) {
cache.delete(items[0]).then(() => {
clearCache(cacheName, maxItemSize)
})
}
})
})
}
self.addEventListener('install', (event) => {
const inmutablePromise = caches.open(INMUTABLE_CACHE)
.then((cache) => {
return cache.addAll([
'https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap',
'https://fonts.googleapis.com/icon?family=Material+Icons',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/full.css',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css',
'https://fonts.gstatic.com/s/materialicons/v139/flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2',
'https://fonts.gstatic.com/s/materialicons/v139/flUhRq6tzZclQEJ-Vdg-IuiaDsNcIhQ8tQ.woff2',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/pouchdb.min.js'
])
});
const staticPromise = caches.open(STATIC_CACHE)
.then((cache) => {
return cache.addAll([
'/',
'/index.html',
'/dashboard.html',
'/observations.html',
'add-observation.html',
'/order.html',
'/products.html',
'/current-products.html',
'/completed-visits.html',
'/next-visits.html',
'/pending-visits.html',
'/template405.html',
'/js/modules/CompletedVisitModule.js',
'/js/modules/NextVisitModule.js',
'/js/modules/PendingVisitModule.js',
'/js/modules/LoginModule.js',
'/js/modules/LogoutModule.js',
'/js/modules/ProductModule.js',
'/js/modules/OrderModule.js',
'/js/modules/ProductsInOrderModule.js',
'/js/modules/ObservationModule.js',
'/js/modules/AddObservationModule.js',
'/js/services/ObservationService.js',
'/js/services/OrderService.js',
'/js/services/ProductService.js',
'/js/services/LoginService.js',
'/js/services/VisitService.js',
'/js/utils/network.js',
'/js/utils/Camera.js',
'/js/utils/api.js',
'/js/utils/sw-db.js',
'/js/utils/notiflix-3.2.5.min.css',
'/js/utils/notiflix-3.2.5.min.js',
'/js/app.js',
'/sw.js',
'/tailwind.config.js',
'/dist/output.css',
'/manifest.json',
'/images/Card 1.svg',
'/images/Card 2.svg',
'/images/Card 3.svg',
'/images/Logo.png',
'/images/london.jpg',
'/images/candies.png',
'/images/dulce-blueprint.png',
'/images/icons/android-launchericon-48-48.png',
'/images/icons/android-launchericon-72-72.png',
'/images/icons/android-launchericon-96-96.png',
'/images/icons/android-launchericon-144-144.png',
'/images/icons/android-launchericon-192-192.png',
'/images/icons/android-launchericon-512-512.png',
])
});
event.waitUntil(Promise.all([inmutablePromise, staticPromise]))
})
self.addEventListener('activate', (event) => {
const promDeleteCaches = caches.keys().then((items) => {
items.forEach((key) => {
if (key !== STATIC_CACHE && key.includes('static')) {
return caches.delete(key);
}
});
});
event.waitUntil(promDeleteCaches);
});
self.addEventListener('fetch', (event) => {
//Metodo global para controlar posts o puts, los get van al else.
if (event.request.clone().method === 'POST' || event.request.clone().method === 'PUT') {
//Respuesta generica en caso de que:
//1 (then): Hay conexión a internet
//2: (catch): No hay conexion para retornar un response personalizado que se guardaró en pouchDB
let genericResponse = fetch(event.request.clone())
.then((response) => {
return response
})
.catch((err) => {
//registramos un evento de sincronización cuando recupere internet (como un listener)
if (self.registration.sync.register('online')) {
return event.request.clone().json().then((json) => {
return savePostOffline(
json,
event.request.url,
event.request.method,
event.request.headers.get("Authorization")
)
})
}
})
event.respondWith(genericResponse)
} else {
event.respondWith(
fetch(event.request)
.then((networkResponse) => {
//Almacenamos la nueva peticion que no estaba en cache
//Y verificamos que el recurso que se va a guardar no sea del cache estatico o inmutable
caches.open(INMUTABLE_CACHE).then((inmutable) => {
inmutable.match(event.request).then((inInmutableExist) => {
if (inInmutableExist === undefined) {
caches.open(STATIC_CACHE).then((static) => {
static.match(event.request).then((inStaticExist) => {
if (inStaticExist === undefined) {
caches.open(DYNAMYC_CACHE).then((cache) => {
cache.put(event.request, networkResponse);
clearCache(DYNAMYC_CACHE, 90)
})
}
})
})
}
})
})
return networkResponse.clone()
})
.catch((err) => {
return caches.match(event.request).then((cacheSource) => {
//Si el recurso no es undefined esta en cache
//Caso contrario, es algo que no estaba en cache (ruta dinamica o recurso al que no se accedio)
if (cacheSource === undefined) {
return caches.match('/template405.html')
.then((respCache) => {
return respCache
})
} else {
return cacheSource
}
})
})
)
}
})
self.addEventListener('sync', (event) => {
//Cuando se recupere conexion, se ejecuta el evento
if (event.tag == "online") {
event.waitUntil(
//Obtenemos todos los documentos de pouchDB y lo mandamos a internet
getAllPostOffline().then((document) => {
document.rows.map((item, i) => {
fetch(item.doc.url, {
method: item.doc.method,
headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': item.doc.token
},
body: JSON.stringify(item.doc.body)
})
.then((response) => {
//En caso de que se hizo el post correctamente, borramos el documento de pouchDB
db.remove(item.doc._id, item.doc._rev);
})
.catch((err) => {
console.log(err)
})
})
})
)
}
})