· 6 years ago · Dec 02, 2019, 10:50 PM
1// Przed
2import Health from '../models/Health';
3import HealthInfo from '../models/HealthInfo';
4
5import { getDistance } from 'geolib';
6
7/**
8 * Fetches health points from Google Places Api
9 * @function getHealthAPI
10 * @param {string} hospitalUrl - url for fetching hospitals
11 * @param {string} pharmacyUrl - url for fetching pharmacies
12 * @param {Object} location - coordinates in an object
13 */
14export const getHealthAPI = async (hospitalUrl, pharmacyUrl, location) => {
15 let response = { data: [], error: null };
16
17 /**
18 * Gets photo url reference
19 * @function getPhotoReference
20 * @param {string} reference - photo reference
21 */
22 const getPhotoReference = reference => {
23 return (
24 'https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=' +
25 reference +
26 '&key=AIzaSyDuOBfyT-kK10-vQjBEED3aUWG_s0_DwoE'
27 );
28 };
29
30 await fetch(hospitalUrl)
31 .then(response => response.json())
32 .then(responseJSON => {
33 const googleHealths = responseJSON.results;
34 for (key in responseJSON.results) {
35 let health = googleHealths[key];
36 response.data.push(
37 new Health(
38 health.id,
39 health.place_id,
40 'Szpital',
41 health.hasOwnProperty('photos') ? getPhotoReference(health.photos[0].photo_reference) : null,
42 health.name,
43 health.geometry.location.lat,
44 health.geometry.location.lng,
45 true,
46 health.vicinity,
47 (location !== null) ?
48 getDistance(location, { lat: health.geometry.location.lat, lng: health.geometry.location.lng }) :
49 null
50 ),
51 );
52 }
53 })
54 .catch(error => {
55 response.error = error
56 });
57
58 await fetch(pharmacyUrl)
59 .then(response => response.json())
60 .then(responseJSON => {
61 const googleHealths = responseJSON.results;
62 for (key in responseJSON.results) {
63 let health = googleHealths[key];
64 response.data.push(
65 new Health(
66 health.id,
67 health.place_id,
68 'Apteka',
69 health.hasOwnProperty('photos') ? getPhotoReference(health.photos[0].photo_reference) : null,
70 health.name,
71 health.geometry.location.lat,
72 health.geometry.location.lng,
73 true,
74 health.vicinity,
75 (location !== null) ?
76 getDistance(location, { lat: health.geometry.location.lat, lng: health.geometry.location.lng }) :
77 null
78 ),
79 );
80 }
81 })
82 .catch(error => {
83 response.error = error
84 });
85 return response;
86};
87
88/**
89 * Get health point's details from Google Api
90 * @function getHealthDetailsAPI
91 * @param {String} url - Google Api url
92 */
93export const getHealthDetailsAPI = async url => {
94 let response = { data: {}, error: null };
95
96 const getOpeningHours = openingHours => {
97 const nameDayArray = ['Pon', 'Wt', 'Sr', 'Czw', 'Pt', 'Sb', 'Nd'];
98 var countEqualDay = 0;
99 const weekday = {};
100 const response = {};
101 openingHours.map((item, index) => {
102 weekday[index] = item.split(': ')[1];
103 });
104
105 for (key in weekday) {
106 const indexNameDayArray = parseInt(key);
107 const nextItemIndex = (parseInt(key) + 1).toString();
108 const responseProp = nameDayArray[indexNameDayArray - countEqualDay];
109 const responseProp2 = nameDayArray[indexNameDayArray];
110 const prop = responseProp + '-' + responseProp2;
111
112 if (nextItemIndex !== '7') {
113 if (weekday[key] !== weekday[nextItemIndex]) {
114 if (countEqualDay === 0) {
115 if (weekday[key] !== 'Closed') {
116 response[responseProp] = weekday[key];
117 } else {
118 response[responseProp] = null;
119 }
120 } else {
121 if (weekday[key] !== 'Closed') {
122 response[prop] = weekday[key];
123 } else {
124 response[prop] = null;
125 }
126 }
127 countEqualDay = 0;
128 } else {
129 countEqualDay = countEqualDay + 1;
130 }
131 } else {
132 if (countEqualDay === 0) {
133 if (weekday[key] !== 'Closed') {
134 response[responseProp] = weekday[key];
135 } else {
136 response[responseProp] = null;
137 }
138 } else {
139 if (weekday[key] !== 'Closed') {
140 response[prop] = weekday[key];
141 } else {
142 response[prop] = null;
143 }
144 }
145 }
146 }
147 return response;
148 };
149
150 const getOtherInfo = (openingHours, phone, website) => {
151 return {
152 phone: phone,
153 openingHours: openingHours !== null ? getOpeningHours(openingHours) : null,
154 website: website,
155 };
156 };
157
158 await fetch(url)
159 .then(response => response.json())
160 .then(responseJSON => {
161 const health = responseJSON.result;
162 const otherInfo = getOtherInfo(
163 (health.hasOwnProperty('opening_hours') ? health.opening_hours.weekday_text : null),
164 (health.hasOwnProperty('international_phone_number') ? health.international_phone_number : null),
165 (health.hasOwnProperty('website') ? health.website : null)
166 );
167 let healthInfo = new HealthInfo(
168 health.place_id,
169 health.name,
170 health.geometry.location.lat,
171 health.geometry.location.lng,
172 otherInfo.phone,
173 otherInfo.openingHours,
174 otherInfo.website,
175 );
176 Object.assign(response.data, healthInfo);
177 })
178 .catch(error => {
179 response.error = error;
180 });
181 return JSON.parse(JSON.stringify(response));
182};
183
184
185
186// Po
187import Health from '../models/Health';
188import HealthInfo from '../models/HealthInfo';
189
190import { getDistance } from 'geolib';
191
192import { GOOGLE_API_KEY } from '../utils/Labels';
193
194export const getHealthApi = async (hospitalURL) => {
195 // Ta zmienna może być const
196 // Nie modyfikujesz jej
197 // Pushujesz dane do response.data - czyli dodajesz do tablicy, ale nie nadpisujesz początkowej wartości tej zmiennej
198 // Początkową wartością zmiennej jest { data: [], error: null }
199 // Konsola nie wyrzuci błędu jeżeli zastosujesz response.data.push();
200 // Na podobnej zasadzie działa useState w React
201 const response = { data: [], error: null };
202
203 // funkcja ma w nazwie _, ponieważ jest ona dostępna tylko w zasięgu funkcji getHealthApi
204 // Jest ona prywanta, więc można zrobić to w ten sposób i nie będzie ona nigdzie indziej wykorzystywana
205 // Nazwy funkcji powinny wskazywać na to co robią
206 // np. getSomething - powinna mieć w nazwie:
207 // get - pobieram
208 // Something - opis tego co pobieram, w tym przypadku PhotoUrlReferrence
209 // String ten nie musi być w nawiasach
210 // Stringi można zapisywać w `` i używać ${} do zmiennych, dzięki czemu nie trzeba bawić się w +
211 // Można skrócić tego stringa dzieląc go na poszczegolne zmienne
212 // Np. wyciągnąć klucz ze stringa i dać go jako zmienną nawet jeżeli nie jest ona wykorzystywana nigdzie indziej
213 // Dzięki temu string staje się krótszy, a kod jeszcze bardziej czytelny
214 // Funckja ta zwraca tylko jednego stringa, nic więcej nie robi, więc nie trzeba korzystać z {} i return, ponieważ funkcja strzałkowa sama zwraca pierwszą rzecz jaka jest po niej
215 // return (
216 // 'https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=' +
217 // reference +
218 // '&key=AIzaSyDuOBfyT-kK10-vQjBEED3aUWG_s0_DwoE'
219 // );
220 const _getPhotoUrlReference = (reference) =>
221 `https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=${reference}&key=${GOOGLE_API_KEY}`;
222
223 // Ogólnie pokusibym się na skorzystanie z try...catch
224 // Wykorzystanie notacji async await jest dużo bardziej czytelna od promise
225 // res.json() także zwraca promise, dlatego trzeb poczekać (await) na niego
226 try {
227 const res = await fetch(hospitalURL); // zapisuję response do zmiennej, która przechowuje response
228 const data = await res.json(); // zapisuję dane do kolejnej zmiennej, która przechowuje data
229
230 const googleHealths = data.results;
231 // Zapisujesz do zmiennej googleHealts data.results
232 // W pętli możesz użyć już zmiennej googleHealths, nie musisz znowu pisać res.results
233 for (key in googleHealths) {
234 const health = googleHealths[key]; // Ta zmienna może być na spokojnie const, nie zmienia ona wartość z każdym przebiegiem pętli, czyli zasada const nie jest naruszona
235 response.data.push(
236 new Health(
237 health.id,
238 health.place_id,
239 'Szpital',
240 health.hasOwnProperty('photos') ? _getPhotoUrlReference(health.photos[0].photo_reference) : null,
241 health.name,
242 health.geometry.location.lat,
243 health.geometry.location.lng,
244 true,
245 health.vicinity,
246 location !== null
247 ? getDistance(location, {
248 lat: health.geometry.location.lat,
249 lng: health.geometry.location.lng
250 })
251 : null
252 )
253 );
254 }
255 } catch (err) {
256 response.error = err;
257 }
258};