-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
967 lines (882 loc) · 26.6 KB
/
server.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
const express = require('express');
const { Pool } = require('pg');
const path = require('path');
const { auth, requiresAuth } = require('express-openid-connect');
const app = express();
const PORT = 3000;
require('dotenv').config();
// Auth0 configuration
const config = {
authRequired: false,
auth0Logout: true,
secret: process.env.AUTH0_SECRET,
baseURL: process.env.AUTH0_BASE_URL,
clientID: process.env.AUTH0_CLIENT_ID,
issuerBaseURL: process.env.AUTH0_ISSUER_BASE_URL
};
// PostgreSQL configuration
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'ORlabDB',
password: 'admin',
port: 5432,
});
// Middleware to parse JSON bodies
app.use(express.json());
// Auth0 middleware
app.use(auth(config));
// Middleware to wrap responses
app.use((req, res, next) => {
const ignoredPaths = ['/', '/dataset', '/punionice.json', '/punionice.csv', '/data', '/profile', '/refresh'];
if (!ignoredPaths.includes(req.path)) {
res.wrap = (status, message, data = null) => {
res.status(status).json({
status: status === 200 ? 'OK' : 'Error',
message,
response: data,
});
};
res.setHeader('Content-Type', 'application/json');
}
next();
});
// Middleware to handle unsupported HTTP methods
app.use((req, res, next) => {
res.methodNotAllowed = () => {
res.wrap(501, 'Method not implemented for requested resource');
};
next();
});
// Serve static files from the "public" directory
app.use(express.static(path.join(__dirname, 'public')));
// Define a route to get data from the database with optional search and column filtering
app.get('/data', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM punionica JOIN stanicazapunjenje ON punionica.id_punionice = stanicazapunjenje.id_punionice');
res.status(200).json(result.rows);
} catch (err) {
console.error(err);
res.wrap(500, 'Server Error');
}
});
// Route to serve the homepage
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'home.html'));
});
// Route to serve the dataset page
app.get('/dataset', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'datatable.html'));
});
// Route to download JSON file
app.get('/punionice.json', (req, res) => {
res.setHeader('Content-Disposition', 'attachment; filename="punionice.json"');
res.sendFile(path.join(__dirname, 'punionice.json'));
});
// Route to download CSV file
app.get('/punionice.csv', (req, res) => {
res.setHeader('Content-Disposition', 'attachment; filename="punionice.csv"');
res.sendFile(path.join(__dirname, 'punionice.csv'));
});
// Route to handle login
app.get('/login', (req, res) => {
res.oidc.login({ returnTo: '/' });
});
// Route to handle logout
app.get('/logout', (req, res) => {
res.oidc.logout({ returnTo: '/' });
});
// Route to handle Auth0 callback
app.get('/callback', (req, res) => {
res.oidc.callback({ redirectUri: '/' });
});
// Route to serve the profile page
app.get('/profile', requiresAuth(), (req, res) => {
res.send(`<h1>Profile</h1><pre>${JSON.stringify(req.oidc.user, null, 2)}</pre>`);
});
// Route to refresh data
app.get('/refresh', requiresAuth(), async (req, res) => {
try {
const result = await pool.query('SELECT * FROM punionica JOIN stanicazapunjenje ON punionica.id_punionice = stanicazapunjenje.id_punionice');
const jsonData = JSON.stringify(result.rows);
const csvData = result.rows.map(row => Object.values(row).join(',')).join('\n');
require('fs').writeFileSync('punionice.json', jsonData);
require('fs').writeFileSync('punionice.csv', csvData);
res.send('Data refreshed');
console.log("Data refreshed " + result.rows.length);
} catch (err) {
console.error(err);
res.status(500).send('Server Error');
}
});
// Helper function to add hypermedia links to a station object
function addLinksToStation(station) {
return {
...station,
links: [
{
href: `/stations/${station.id_punionice}`,
rel: 'self',
type: 'GET',
},
{
href: `/stations/${station.id_punionice}`,
rel: 'update',
type: 'PUT',
},
{
href: `/stations/${station.id_punionice}`,
rel: 'delete',
type: 'DELETE',
},
],
};
}
// Helper function to parse address
function parseAddress(address) {
const [streetAddress, postalCode, addressLocality] = address.split(',').map(part => part.trim());
let addressRegion = "";
if (address.includes("Zagreb")) {
addressRegion = "Zagreb";
} else if (address.includes("Osijek")) {
addressRegion = "Osijek";
}
const addressCountry = "Croatia"; // Assuming the country is Croatia for all addresses
return { streetAddress, postalCode, addressLocality, addressRegion, addressCountry };
}
// Get all charging stations
app.get('/stations', async (req, res) => {
try {
const result = await pool.query(`
SELECT
p.id_punionice,
p.naziv_punionice,
p.adresa,
p.geografska_sirina,
p.geografska_duzina,
p.vrsta_punjenja,
p.broj_punjaca,
p.snaga_punjenja,
p.cijena_po_kwh,
p.otvorenje,
p.zatvaranje,
s.id_stanice,
s.tip_konektora,
s.snaga_stanice,
s.pruzatelj
FROM punionica p
LEFT JOIN stanicazapunjenje s ON p.id_punionice = s.id_punionice
`);
const stations = result.rows.reduce((acc, row) => {
const {
id_punionice,
naziv_punionice,
adresa,
geografska_sirina,
geografska_duzina,
vrsta_punjenja,
broj_punjaca,
snaga_punjenja,
cijena_po_kwh,
otvorenje,
zatvaranje,
id_stanice,
tip_konektora,
snaga_stanice,
pruzatelj
} = row;
const { streetAddress, postalCode, addressLocality, addressRegion, addressCountry } = parseAddress(adresa);
if (!acc[id_punionice]) {
acc[id_punionice] = {
"@context": "https://schema.org",
"@type": "Place",
"name": naziv_punionice,
"address": {
"@type": "PostalAddress",
"streetAddress": streetAddress,
"addressLocality": addressLocality,
"addressRegion": addressRegion,
"postalCode": postalCode,
"addressCountry": addressCountry
},
"geo": {
"@type": "GeoCoordinates",
"latitude": geografska_sirina,
"longitude": geografska_duzina
},
"chargingStation": {
"@type": "ElectricVehicleChargingStation",
"name": naziv_punionice,
"address": {
"@type": "PostalAddress",
"streetAddress": streetAddress,
"addressLocality": addressLocality,
"addressRegion": addressRegion,
"postalCode": postalCode,
"addressCountry": addressCountry
},
"geo": {
"@type": "GeoCoordinates",
"latitude": geografska_sirina,
"longitude": geografska_duzina
},
"numberOfChargingPoints": broj_punjaca,
"chargingPointCapacity": snaga_punjenja,
"pricePerKWh": cijena_po_kwh,
"openingHours": otvorenje,
"closingHours": zatvaranje,
"stanicazapunjenje": [] // Initialize the array here
}
};
}
if (id_stanice) {
acc[id_punionice].chargingStation.stanicazapunjenje.push({
id_stanice,
tip_konektora,
snaga_stanice,
pruzatelj
});
}
return acc;
}, {});
const stationsArray = Object.values(stations).map(addLinksToStation);
res.wrap(200, 'List of all charging stations', stationsArray);
} catch (err) {
res.wrap(500, err.message);
}
});
// Get a charging station by ID
app.get('/stations/:id_punionice', async (req, res) => {
try {
const result = await pool.query(`
SELECT
p.id_punionice,
p.naziv_punionice,
p.adresa,
p.geografska_sirina,
p.geografska_duzina,
p.vrsta_punjenja,
p.broj_punjaca,
p.snaga_punjenja,
p.cijena_po_kwh,
p.otvorenje,
p.zatvaranje,
s.id_stanice,
s.tip_konektora,
s.snaga_stanice,
s.pruzatelj
FROM punionica p
LEFT JOIN stanicazapunjenje s ON p.id_punionice = s.id_punionice
WHERE p.id_punionice = $1
`, [parseInt(req.params.id_punionice)]);
if (result.rows.length > 0) {
const station = result.rows.reduce((acc, row) => {
const {
id_punionice,
naziv_punionice,
adresa,
geografska_sirina,
geografska_duzina,
vrsta_punjenja,
broj_punjaca,
snaga_punjenja,
cijena_po_kwh,
otvorenje,
zatvaranje,
id_stanice,
tip_konektora,
snaga_stanice,
pruzatelj
} = row;
const { streetAddress, postalCode, addressLocality, addressRegion, addressCountry } = parseAddress(adresa);
if (!acc) {
acc = {
"@context": "https://schema.org",
"@type": "Place",
"name": naziv_punionice,
"address": {
"@type": "PostalAddress",
"streetAddress": streetAddress,
"addressLocality": addressLocality,
"addressRegion": addressRegion,
"postalCode": postalCode,
"addressCountry": addressCountry
},
"geo": {
"@type": "GeoCoordinates",
"latitude": geografska_sirina,
"longitude": geografska_duzina
},
"chargingStation": {
"@type": "ElectricVehicleChargingStation",
"name": naziv_punionice,
"address": {
"@type": "PostalAddress",
"streetAddress": streetAddress,
"addressLocality": addressLocality,
"addressRegion": addressRegion,
"postalCode": postalCode,
"addressCountry": addressCountry
},
"geo": {
"@type": "GeoCoordinates",
"latitude": geografska_sirina,
"longitude": geografska_duzina
},
"numberOfChargingPoints": broj_punjaca,
"chargingPointCapacity": snaga_punjenja,
"pricePerKWh": cijena_po_kwh,
"openingHours": otvorenje,
"closingHours": zatvaranje,
"stanicazapunjenje": []
}
};
}
if (id_stanice) {
acc.chargingStation.stanicazapunjenje.push({
id_stanice,
tip_konektora,
snaga_stanice,
pruzatelj
});
}
return acc;
}, null);
const stationWithLinks = addLinksToStation(station);
res.wrap(200, 'Station found', stationWithLinks);
} else {
res.wrap(404, 'Station not found');
}
} catch (err) {
res.wrap(500, err.message);
}
});
// Get a charging station by ID
app.get('/stations/:id_punionice', async (req, res) => {
try {
const result = await pool.query(`
SELECT
p.id_punionice,
p.naziv_punionice,
p.adresa,
p.geografska_sirina,
p.geografska_duzina,
p.vrsta_punjenja,
p.broj_punjaca,
p.snaga_punjenja,
p.cijena_po_kwh,
p.otvorenje,
p.zatvaranje,
s.id_stanice,
s.tip_konektora,
s.snaga_stanice,
s.pruzatelj
FROM punionica p
LEFT JOIN stanicazapunjenje s ON p.id_punionice = s.id_punionice
WHERE p.id_punionice = $1
`, [parseInt(req.params.id_punionice)]);
if (result.rows.length > 0) {
const station = result.rows.reduce((acc, row) => {
const {
id_punionice,
naziv_punionice,
adresa,
geografska_sirina,
geografska_duzina,
vrsta_punjenja,
broj_punjaca,
snaga_punjenja,
cijena_po_kwh,
otvorenje,
zatvaranje,
id_stanice,
tip_konektora,
snaga_stanice,
pruzatelj
} = row;
const { streetAddress, postalCode, addressLocality, addressRegion, addressCountry } = parseAddress(adresa);
if (!acc) {
acc = {
"@context": "https://schema.org",
"@type": "Place",
"name": naziv_punionice,
"address": {
"@type": "PostalAddress",
"streetAddress": streetAddress,
"addressLocality": addressLocality,
"addressRegion": addressRegion,
"postalCode": postalCode,
"addressCountry": addressCountry
},
"geo": {
"@type": "GeoCoordinates",
"latitude": geografska_sirina,
"longitude": geografska_duzina
},
"chargingStation": {
"@type": "ElectricVehicleChargingStation",
"name": naziv_punionice,
"address": {
"@type": "PostalAddress",
"streetAddress": streetAddress,
"addressLocality": addressLocality,
"addressRegion": addressRegion,
"postalCode": postalCode,
"addressCountry": addressCountry
},
"geo": {
"@type": "GeoCoordinates",
"latitude": geografska_sirina,
"longitude": geografska_duzina
},
"numberOfChargingPoints": broj_punjaca,
"chargingPointCapacity": snaga_punjenja,
"pricePerKWh": cijena_po_kwh,
"openingHours": otvorenje,
"closingHours": zatvaranje,
"stanicazapunjenje": []
}
};
}
if (id_stanice) {
acc.chargingStation.stanicazapunjenje.push({
id_stanice,
tip_konektora,
snaga_stanice,
pruzatelj
});
}
return acc;
}, null);
const stationWithLinks = addLinksToStation(station);
res.wrap(200, 'Station found', stationWithLinks);
} else {
res.wrap(404, 'Station not found');
}
} catch (err) {
res.wrap(500, err.message);
}
});
// Add a new charging station
app.post('/stations', async (req, res) => {
const {
naziv_punionice,
adresa,
geografska_sirina,
geografska_duzina,
vrsta_punjenja,
broj_punjaca,
snaga_punjenja,
cijena_po_kwh,
otvorenje,
zatvaranje,
stanicazapunjenje // This should be an array of objects
} = req.body;
try {
await pool.query('BEGIN');
const punionicaResult = await pool.query(
'INSERT INTO punionica (naziv_punionice, adresa, geografska_sirina, geografska_duzina, vrsta_punjenja, broj_punjaca, snaga_punjenja, cijena_po_kwh, otvorenje, zatvaranje) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING id_punionice',
[
naziv_punionice,
adresa,
geografska_sirina,
geografska_duzina,
vrsta_punjenja,
broj_punjaca,
snaga_punjenja,
cijena_po_kwh,
otvorenje,
zatvaranje
]
);
const id_punionice = punionicaResult.rows[0].id_punionice;
// Insert new stanicazapunjenje entries
for (const stanica of stanicazapunjenje) {
await pool.query(
'INSERT INTO stanicazapunjenje (id_punionice, tip_konektora, snaga_stanice, pruzatelj) VALUES ($1, $2, $3, $4) RETURNING *',
[
id_punionice,
stanica.tip_konektora,
stanica.snaga_stanice,
stanica.pruzatelj
]
);
}
await pool.query('COMMIT');
// Fetch the newly added station with its stanicazapunjenje
const newStationResult = await pool.query(`
SELECT
p.id_punionice,
p.naziv_punionice,
p.adresa,
p.geografska_sirina,
p.geografska_duzina,
p.vrsta_punjenja,
p.broj_punjaca,
p.snaga_punjenja,
p.cijena_po_kwh,
p.otvorenje,
p.zatvaranje,
s.id_stanice,
s.tip_konektora,
s.snaga_stanice,
s.pruzatelj
FROM punionica p
LEFT JOIN stanicazapunjenje s ON p.id_punionice = s.id_punionice
WHERE p.id_punionice = $1
`, [id_punionice]);
const newStation = newStationResult.rows.reduce((acc, row) => {
const {
id_punionice,
naziv_punionice,
adresa,
geografska_sirina,
geografska_duzina,
vrsta_punjenja,
broj_punjaca,
snaga_punjenja,
cijena_po_kwh,
otvorenje,
zatvaranje,
id_stanice,
tip_konektora,
snaga_stanice,
pruzatelj
} = row;
if (!acc) {
acc = {
id_punionice,
naziv_punionice,
adresa,
geografska_sirina,
geografska_duzina,
vrsta_punjenja,
broj_punjaca,
snaga_punjenja,
cijena_po_kwh,
otvorenje,
zatvaranje,
stanicazapunjenje: []
};
}
if (id_stanice) {
acc.stanicazapunjenje.push({
id_stanice,
tip_konektora,
snaga_stanice,
pruzatelj
});
}
return acc;
}, null);
const stationWithLinks = addLinksToStation(newStation);
res.wrap(200, 'Station added successfully', stationWithLinks);
} catch (err) {
await pool.query('ROLLBACK');
res.wrap(500, err.message);
}
});
// Get a charging station by ID
app.get('/stations/:id_punionice', async (req, res) => {
try {
const result = await pool.query(`
SELECT
p.id_punionice,
p.naziv_punionice,
p.adresa,
p.geografska_sirina,
p.geografska_duzina,
p.vrsta_punjenja,
p.broj_punjaca,
p.snaga_punjenja,
p.cijena_po_kwh,
p.otvorenje,
p.zatvaranje,
s.id_stanice,
s.tip_konektora,
s.snaga_stanice,
s.pruzatelj
FROM punionica p
LEFT JOIN stanicazapunjenje s ON p.id_punionice = s.id_punionice
WHERE p.id_punionice = $1
`, [parseInt(req.params.id_punionice)]);
if (result.rows.length > 0) {
const station = result.rows.reduce((acc, row) => {
const {
id_punionice,
naziv_punionice,
adresa,
geografska_sirina,
geografska_duzina,
vrsta_punjenja,
broj_punjaca,
snaga_punjenja,
cijena_po_kwh,
otvorenje,
zatvaranje,
id_stanice,
tip_konektora,
snaga_stanice,
pruzatelj
} = row;
if (!acc) {
acc = {
"@context": "https://schema.org",
"@type": "Place",
"name": naziv_punionice,
"address": {
"@type": "PostalAddress",
"streetAddress": adresa,
"addressLocality": "Grad",
"addressRegion": "Regija",
"postalCode": "Poštanski broj",
"addressCountry": "Država"
},
"geo": {
"@type": "GeoCoordinates",
"latitude": geografska_sirina,
"longitude": geografska_duzina
},
"additionalType": "https://schema.org/ElectricVehicleChargingStation",
"chargingStation": {
"@type": "ElectricVehicleChargingStation",
"name": naziv_punionice,
"address": {
"@type": "PostalAddress",
"streetAddress": adresa,
"addressLocality": "Grad",
"addressRegion": "Regija",
"postalCode": "Poštanski broj",
"addressCountry": "Država"
},
"geo": {
"@type": "GeoCoordinates",
"latitude": geografska_sirina,
"longitude": geografska_duzina
},
"numberOfChargingPoints": broj_punjaca,
"chargingPointCapacity": snaga_punjenja,
"pricePerKWh": cijena_po_kwh,
"openingHours": otvorenje,
"closingHours": zatvaranje,
"stanicazapunjenje": []
}
};
}
if (id_stanice) {
acc.chargingStation.stanicazapunjenje.push({
id_stanice,
tip_konektora,
snaga_stanice,
pruzatelj
});
}
return acc;
}, null);
const stationWithLinks = addLinksToStation(station);
res.wrap(200, 'Station found', stationWithLinks);
} else {
res.wrap(404, 'Station not found');
}
} catch (err) {
res.wrap(500, err.message);
}
});
// Update a charging station by ID
app.put('/stations/:id_punionice', async (req, res) => {
const {
naziv_punionice,
adresa,
geografska_sirina,
geografska_duzina,
vrsta_punjenja,
broj_punjaca,
snaga_punjenja,
cijena_po_kwh,
otvorenje,
zatvaranje,
stanicazapunjenje // This should be an array of objects
} = req.body;
const { id_punionice } = req.params;
try {
await pool.query('BEGIN');
const punionicaResult = await pool.query(
'UPDATE punionica SET naziv_punionice = $1, adresa = $2, geografska_sirina = $3, geografska_duzina = $4, vrsta_punjenja = $5, broj_punjaca = $6, snaga_punjenja = $7, cijena_po_kwh = $8, otvorenje = $9, zatvaranje = $10 WHERE id_punionice = $11 RETURNING *',
[
naziv_punionice,
adresa,
geografska_sirina,
geografska_duzina,
vrsta_punjenja,
broj_punjaca,
snaga_punjenja,
cijena_po_kwh,
otvorenje,
zatvaranje,
id_punionice
]
);
// Delete existing stanicazapunjenje entries for the station
await pool.query(
'DELETE FROM stanicazapunjenje WHERE id_punionice = $1',
[id_punionice]
);
// Insert new stanicazapunjenje entries
for (const stanica of stanicazapunjenje) {
await pool.query(
'INSERT INTO stanicazapunjenje (id_punionice, tip_konektora, snaga_stanice, pruzatelj) VALUES ($1, $2, $3, $4)',
[
id_punionice,
stanica.tip_konektora,
stanica.snaga_stanice,
stanica.pruzatelj
]
);
}
await pool.query('COMMIT');
// Fetch the updated station with its stanicazapunjenje
const updatedStationResult = await pool.query(`
SELECT
p.id_punionice,
p.naziv_punionice,
p.adresa,
p.geografska_sirina,
p.geografska_duzina,
p.vrsta_punjenja,
p.broj_punjaca,
p.snaga_punjenja,
p.cijena_po_kwh,
p.otvorenje,
p.zatvaranje,
s.id_stanice,
s.tip_konektora,
s.snaga_stanice,
s.pruzatelj
FROM punionica p
LEFT JOIN stanicazapunjenje s ON p.id_punionice = s.id_punionice
WHERE p.id_punionice = $1
`, [id_punionice]);
const updatedStation = updatedStationResult.rows.reduce((acc, row) => {
const {
id_punionice,
naziv_punionice,
adresa,
geografska_sirina,
geografska_duzina,
vrsta_punjenja,
broj_punjaca,
snaga_punjenja,
cijena_po_kwh,
otvorenje,
zatvaranje,
id_stanice,
tip_konektora,
snaga_stanice,
pruzatelj
} = row;
if (!acc) {
acc = {
id_punionice,
naziv_punionice,
adresa,
geografska_sirina,
geografska_duzina,
vrsta_punjenja,
broj_punjaca,
snaga_punjenja,
cijena_po_kwh,
otvorenje,
zatvaranje,
stanicazapunjenje: []
};
}
if (id_stanice) {
acc.stanicazapunjenje.push({
id_stanice,
tip_konektora,
snaga_stanice,
pruzatelj
});
}
return acc;
}, null);
const stationWithLinks = addLinksToStation(updatedStation);
res.wrap(200, 'Station updated successfully', stationWithLinks);
} catch (err) {
await pool.query('ROLLBACK');
res.wrap(500, err.message);
}
});
// Delete a charging station by ID
app.delete('/stations/:id_punionice', async (req, res) => {
const { id_punionice } = req.params;
try {
await pool.query('BEGIN');
const stanicazapunjenjeResult = await pool.query(
'DELETE FROM stanicazapunjenje WHERE id_punionice = $1 RETURNING *',
[parseInt(id_punionice)]
);
const punionicaResult = await pool.query(
'DELETE FROM punionica WHERE id_punionice = $1 RETURNING *',
[parseInt(id_punionice)]
);
await pool.query('COMMIT');
if (punionicaResult.rows.length > 0) {
res.wrap(200, 'Station deleted successfully', {
links: [
{
href: '/stations',
rel: 'list',
type: 'GET',
},
],
});
} else {
res.wrap(404, "Station with the provided ID doesn't exist");
}
} catch (err) {
await pool.query('ROLLBACK');
res.wrap(500, err.message);
}
});
// Get stations by provider
app.get('/stations/provider/:provider', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM stanicazapunjenje WHERE pruzatelj = $1', [req.params.provider]);
const stations = result.rows.map(addLinksToStation);
res.wrap(200, `List of stations for provider ${req.params.provider}`, stations);
} catch (err) {
res.wrap(500, err.message);
}
});
// Get stations by connector type
app.get('/stations/connector/:connector', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM stanicazapunjenje WHERE tip_konektora = $1', [req.params.connector]);
const stations = result.rows.map(addLinksToStation);
res.wrap(200, `List of stations for connector type ${req.params.connector}`, stations);
} catch (err) {
res.wrap(500, err.message);
}
});
// Get stations by minimum power
app.get('/stations/power/:power', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM stanicazapunjenje WHERE snaga_stanice >= $1', [parseInt(req.params.power)]);
const stations = result.rows.map(addLinksToStation);
res.wrap(200, `List of stations with power above ${req.params.power}`, stations);
} catch (err) {
res.wrap(500, err.message);
}
});
// Handle unsupported HTTP methods
app.all('/stations/:id_punionice', (req, res) => {
res.methodNotAllowed();
});
// Handle non-existent endpoints
app.use((req, res) => {
res.wrap(404, "Unimplemented endpoint");
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});