-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.js
1328 lines (1292 loc) · 45.7 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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
POSTMAN STUDENT EXPERT
This API works in conjunction with the Student expert collection in Postman to walk you through API basics.
Import the collection into Postman and send a request to the setup endpoint to begin.
https://explore.postman.com/templates/11859/student-expert
This Glitch app is based on hello-express and low-db.
Below you'll see the code for the endpoints in the API after some initial setup processing
- each endpoint begins "app." followed by get, post, patch, put, or delete, then the endpoint path, e.g. /cat
*/
/*
response structure:
{
welcome:
"Welcome! Check out the 'data' object below to see the values returned by the API. Click **Visualize** to see the 'tutorial' data " +
"for this request in a more readable view.",
data: {
cat: {
name: "Syd",
humans: 9
}
},
tutorial: {
title: "You did a thing! 🚀",
intro: "Here is the _intro_ to this **lesson**...",
steps: [
{
note: "Here is a step with `code` in it...",
pic:
"https://assets.postman.com/postman-docs/postman-app-overview-response.jpg",
raw_data: {
cat: {
name: "Syd",
humans: 9
}
}
}
],
next: [
{
step: "Now do this...",
pic:
"https://assets.postman.com/postman-docs/postman-app-overview-response.jpg",
raw_data: {
cat: {
name: "Syd",
humans: 9
}
}
}
]
}
}
*/
// server.js
// where your node app starts
const express = require("express");
var bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// setup a new database persisted using async file storage
// Security note: the database is saved to the file `db.json` on the local filesystem.
// It's deliberately placed in the `.data` directory which doesn't get copied if someone remixes the project.
var low = require("lowdb");
var FileSync = require("lowdb/adapters/FileSync");
var adapter = new FileSync(".data/db.json");
var db = low(adapter);
const shortid = require("shortid");
//email validation
var validator = require("email-validator");
//submissions
var multer = require("multer");
var upload = multer();
const sendgridmail = require("@sendgrid/mail");
var request = require("request");
// default list
db.defaults({
matches: [
{
id: shortid.generate(),
creator: "postman",
matchType: "League Cup Semi Final",
opposition: "United",
date: "Wed Mar 24 2021 14: 00: 04 GMT+0000 (Coordinated Universal Time)",
points: -1
},
{
id: shortid.generate(),
creator: "postman",
matchType: "League Cup Quarter Final",
opposition: "City",
date: "Thu Jan 30 2020 20: 50: 46 GMT+0000 (Coordinated Universal Time)",
points: 3
},
{
id: shortid.generate(),
creator: "postman",
matchType: "Friendly",
opposition: "Athletic",
date: "Wed Jan 13 2021 23: 01: 26 GMT+0000 (Coordinated Universal Time)",
points: -1
}
],
calls: [],
submissions: []
}).write();
// http://expressjs.com/en/starter/basic-routing.html
app.get("/", (req, res) => {
var newDate = new Date();
db.get("calls")
.push({
when: newDate.toDateString() + " " + newDate.toTimeString(),
where: "GET /",
what: req.get("match_key")
})
.write();
if (req.headers["user-agent"].includes("Postman"))
res.status(200).json({
welcome: welcomeMsg,
tutorial: {
title: process.env.PROJECT,
intro:
"Use the " +
process.env.PROJECT +
" template in Postman to learn API basics! Import the collection in Postman by clicking " +
"New > Templates, and searching for '" +
process.env.PROJECT +
"'. Open the first request in the collection and click Send. " +
"To see the API code navigate to https://glitch.com/edit/#!/" +
process.env.PROJECT_DOMAIN +
" in your web browser!"
}
});
else
res.send(
"<h1>" +
process.env.PROJECT +
"</h1><p>Oh, hi! There's not much to see here - view the code instead:</p>" +
'<script src="https://button.glitch.me/button.js" data-style="glitch"></script><div class="glitchButton" style="position:fixed;top:20px;right:20px;"></div>'
);
});
//generic welcome message
var welcomeMsg =
"You're using the " +
process.env.PROJECT +
" training course! Check out the 'data' object below to see the values returned by this API request. " +
"Click **Visualize** to see the 'tutorial' guiding you through next steps - do this for every request in the collection!";
//admin unauthorized
var unauthorizedMsg = {
welcome: welcomeMsg,
tutorial: {
title: "Your request is unauthorized! 🚫",
intro: "This endpoint requires admin authorization.",
steps: [
{
note: "This endpoint is only accessible to admins for the API."
}
],
next: [
{
step: "Use the admin key indicated in the project env as secret."
}
]
}
};
//invalid route
var invalidMsg = {
welcome: welcomeMsg,
tutorial: {
title: "Your request is invalid! 🚧",
intro:
"Oops this isn't a valid endpoint! " +
"Try undoing your changes or closing the request without saving and opening it again from the collection on the left of Postman."
}
};
//submission failed
var submissionFailMsg = {
welcome: welcomeMsg,
tutorial: {
title: "Your submission didn't make it! ⛔",
intro: "Oops! Something went wrong with your submission.",
steps: [
{
note:
"Check your request **Body**—it should contain two **form-data* fields: `collection` which should be the collection URL, " +
"and `run` which should be a file you downloaded from the collection runner."
}
],
next: [
{
step: "With your body fields in place, click **Send** again."
}
]
}
};
//intro
app.get("/training", (req, res) => {
var newDate = new Date();
db.get("calls")
.push({
when: newDate.toDateString() + " " + newDate.toTimeString(),
where: "GET /training",
what: req.get("match_key")
})
.write();
res.status(200).json({
welcome: welcomeMsg,
data: {
course: process.env.PROJECT
},
tutorial: {
title: "Welcome to " + process.env.PROJECT + " training! 🎒🎓",
intro:
"This API and the collection you imported into Postman will guide you through the steps required to become a student expert.",
steps: [
{
note:
"The request you sent to the student training API received a response including this data:",
raw_data: {
course: process.env.PROJECT
}
},
{
note:
"The responses will include JSON data that you can see in the **Body > Pretty** area. The **Visualize** view will show you a " +
"more readable view of the information in the response `tutorial` object, including images that will help you understand each step."
},
{
note:
"Throughout the course, you will create, edit, and send requests inside Postman, and the responses will guide you onto next " +
"steps. You will work through the requests in the collection folders, learning API and Postman skills along the way."
}
],
next: [
{
step:
"This folder has two requests in it—open the next one `1. Get matches`, look at the address, then come back to this one."
},
{
step:
"Both requests use the same **base** URL `" +
process.env.PROJECT_DOMAIN +
".glitch.me`—instead of repeating this in every request, let's store it in a variable and reuse the value. Select the part of "+
"the address before `/training` and click **Set as variable** > **Set as a new variable**. Enter `training_api` as the "+
"**Name** with `" +
process.env.PROJECT_DOMAIN +
".glitch.me` " +
"as the **Value**. Select **Collection** for the **Scope**, making sure the correct collection is selected. Click "+
"**Set variable**.",
pic:
"https://assets.postman.com/postman-docs/postman-training-set-as-var.jpg"
},
{
step:
"In the request builder, edit the address, replacing only `postman-student-expert.glitch.me` (the part before `/training`) with "+
"`{{training_api}}`—this is how we " +
"reference variables in requests. Click **Send** to make sure the request still behaves the same way and scroll back here.",
pic:
"https://assets.postman.com/postman-docs/student-expert-url-var.jpg"
},
{
step:
"Before you move on click **Save** to save your request edits. Now open the next request in the collection `Get matches` and do " +
"the same for the URL in there, replacing the base part of address with the variable reference—it should now be " +
"`{{training_api}}/matches`. Click **Send** on the `Get matches` request and remember " +
"to open the **Visualizer** on the response."
}
]
}
});
});
app.get("/matches", (req, res) => {
const apiSecret = req.get("match_key");
var newDate = new Date();
db.get("calls")
.push({
when: newDate.toDateString() + " " + newDate.toTimeString(),
where: "GET /matches",
what: req.query.status + " " + apiSecret
})
.write();
if (req.query.status) {
var matches;
if (!["played", "pending"].includes(req.query.status)) {
res.status(400).json({
welcome: welcomeMsg,
tutorial: {
title: "Your request is incomplete! ✋",
intro: "Status must be `played` or `pending`!",
steps: [
{
note:
"Open **Params** and enter `played` or `pending` as the **Value** for the parameter with `status` as the **Key**. " +
"You will see the query parameter added to the end of the request address e.g. `/matches?status=pending`."
}
],
next: [
{
step:
"With a valid parameter value in place, click **Send** again."
}
]
}
});
} else if (req.query.status === "played") {
matches = db
.get("matches")
.filter(o => o.points > -1)
.filter(o => o.creator === "postman" || o.creator === apiSecret)
.value();
} else if (req.query.status === "pending") {
matches = db
.get("matches")
.filter(o => o.points < 0)
.filter(o => o.creator === "postman" || o.creator === apiSecret)
.value();
}
res.status(200).json({
welcome: welcomeMsg,
data: {
matches: matches
},
tutorial: {
title: "You sent a request to filter the matches returned!",
intro:
"The `status` parameter specified `" +
req.query.status +
"` which filters based on whether a match has been played or not.",
steps: [
{
note:
"This is a typical use of a query parameter—where you are requesting more specific information than the general path. " +
"The API returned the following data:",
raw_data: {
matches: matches
}
},
{
note:
"You could have several query parameters, all of which will be appended to your request address by preceding each with" +
"`&` e.g. `/matches?status=pending&team=United`. This is a pattern you will see in the web browser address bar when you navigate " +
"websites—APIs work the same way."
},
{
note:
"You can use different types of parameter with your requests as you will see in some of the requests you build next. " +
"Before you move on, click **Save** in Postman to save the current state of your request."
}
],
next: [
{
step:
"So far we've retrieved data from the API, but let's also add some new data. Add another request to the collection. In **Collections** " +
"click the *...* on the **1. Begin training - Requests** folder and click **Add Request**–it will open in the request builder. "+
"Name the request '2. Add match'.",
pic:
"https://assets.postman.com/postman-docs/student-expert-add-request.jpg"
},
{
step:
"The new request will appear in the collection folder on the left. In the request builder, enter the URL, " +
"`{{training_api}}/match` and select `POST` from the method drop-down list. Click **Send**.",
pic:
"https://assets.postman.com/postman-docs/student-expert-post-url.jpg"
}
]
}
});
} else {
var matches = db
.get("matches")
.filter(m => m.creator === "postman" || m.creator === apiSecret)
.value();
res.status(200).json({
welcome: welcomeMsg,
data: {
matches: matches
},
tutorial: {
title: "You sent a request to retrieve all matches for the team! 🎉",
intro:
"The demo API we're using for this course is a for a fictional sports team. The API manages match, player, and team data. " +
"The request you just sent uses a `GET` which is for retrieving data.",
steps: [
{
note:
"The request you sent to `/matches` returned the following data. It's an array of the matches currently in the database, " +
"including a few data values for each match.",
raw_data: {
matches: matches
}
},
{
note:
"Open the **Console** along the bottom of the Postman window to see the address the request sent to. You can click a request " +
"in the Console to see the full detail of what happened when it sent - this is helpful when you're troubleshooting. Close and " +
"open the Console area whenever you find it useful."
}
],
next: [
{
step:
"This request retrieved all matches, but you can also filter the matches using parameters. Open **Params** and enter a new Query " +
"parameter, with `status` as the **Key** and `played` or `pending` as the **Value**. You will see the query parameter added to " +
"the end of the request address e.g. `/matches?status=pending`. Click **Send** again.",
pic:
"https://assets.postman.com/postman-docs/student-expert-add-query.jpg"
}
]
}
});
}
});
app.post("/match", (req, res) => {
const apiSecret = req.get("match_key");
var newDate = new Date();
db.get("calls")
.push({
when: newDate.toDateString() + " " + newDate.toTimeString(),
where: "POST /match",
what: req.body.match + " " + apiSecret
})
.write();
console.log(apiSecret);
if (!apiSecret || apiSecret.length < 1 || apiSecret.startsWith("{")) {
res.status(401).json({
welcome: welcomeMsg,
tutorial: {
title: "Oops - You got an unauthorized error response! 🚫",
intro:
"When you're sending new data to the API, you will typically need to authorize your requests.",
steps: [
{
note:
"You're going to add an auth key to this request, but instead of entering it manually let's use a variable—this helps " +
"minimize visibility of what could be sensitive credentials. Open the **Authorization** tab for the request—select " +
"`Inherit auth from parent` from the **Type** drop-down list.",
pic:
"https://assets.postman.com/postman-docs/student-expert-inherit-auth.jpg"
},
{
note:
"In **Collections** on the left, select the student expert collection (click **...** and choose **Edit** if you're in the app). "+
"Open the **Authorization** tab. Postman will add the API key details to the header for every request using the name `match_key` and " +
"the value specified by the referenced `email_key` variable.",
pic:
"https://assets.postman.com/postman-docs/student-expert-auth-details.jpg"
}
],
next: [
{
step:
"Add a variable to the collection also via the **Edit** menu—choosing the **Variables** tab. Use the name `email_key` and enter " +
"your email address in both value fields. Postman will now append your email address to each request to identify you as the client. " +
"**Make sure you use the email address you'd like your Postman Student Expert certification awarded to, e.g. don't use your " +
"college email because you'll no longer have access to that when you graduate—choose a personal email address you'll continue " +
"to have access to.**",
pic:
"https://assets.postman.com/postman-docs/student-expert-email-var-added.jpg"
},
{
step: "If you pop back into the collection edit modal **Authorization** and hover over the `{{email_key}}` reference you should "+
"now see your email address. With your API Key in place, click **Send**."
}
]
}
});
} else if (!validator.validate(apiSecret)) {
res.status(401).json({
welcome: welcomeMsg,
tutorial: {
title: "You got an unauthorized error response!",
intro: "🚫Unauthorized - your key needs to be an email address!",
steps: [
{
note:
"The API will only authorize your requests if your key is a valid email address."
}
],
next: [
{
step:
"Open your collection (**Edit** menu on the desktop app) and navigate to **Variables**. You should have a variable named `email_key`—make sure it's " +
"value is an email address and click **Send** again.",
pic: ""
}
]
}
});
} else {
if (req.body.match && req.body.when && req.body.against) {
const postId = db
.get("matches")
.push({
id: shortid.generate(),
creator: apiSecret,
matchType: req.body.match,
opposition: req.body.against,
date: req.body.when,
points: -1
})
.write().id;
res.status(201).json({
welcome: welcomeMsg,
tutorial: {
title: "You added a new match! 🏅",
intro: "Your new match was added to the database.",
steps: [
{
note:
"Go back into the `Get matches` request, make sure your `status` query parameter is set to `pending`, and that you have **Inherit "+
"auth from parent** selected, then **Send** it again " +
"before returning here—you should see your new addition in the array! _Note that this will only work if you're using the " +
"Postman template._"
}
],
next: [
{
step:
"**Save** your current request, then create another new request still inside the **1. Begin training - Requests** folder. " +
"Give it the name `3. Update score` and save it. In the request builder select `PUT` " +
"method, and enter the URL `{{training_api}}/match`. Click **Send**."
}
]
}
});
} else
res.status(400).json({
welcome: welcomeMsg,
tutorial: {
title: "🚧 Bad request - please check your body data!",
intro: "This endpoint requires body data representing the new match.",
steps: [
{
note:
"In **Body** select **raw** and choose `JSON` instead of `Text` in the drop-down list. Enter the following JSON data " +
"including the enclosing curly braces:",
raw_data: {
match: "Cup Final",
when: "{{$randomDateFuture}}",
against: "Academical"
},
pic:
"https://assets.postman.com/postman-docs/student-expert-body-added.jpg"
},
{
note:
"The `when` value uses a dynamic variable. Postman will add a random future date when you send your request. " +
"There are lots of other dynamic variables you can use in your requests for values you want to calculate at runtime, or if " +
"you want to use demo data instead of real values."
}
],
next: [
{
step: "With your body data in place, click **Send** again."
}
]
}
});
}
});
//update score
app.put("/match", function(req, res) {
const apiSecret = req.get("match_key");
var newDate = new Date();
db.get("calls")
.push({
when: newDate.toDateString() + " " + newDate.toTimeString(),
where: "PUT /match",
what: req.query.match_id + " " + apiSecret
})
.write();
if (!apiSecret)
res.status(401).json({
welcome: welcomeMsg,
tutorial: {
title: "Oops - You got an unauthorized error response! 🚫",
intro:
"You will need to authorize your request just as you did in the `POST` request.",
steps: [
{
note:
"You should already have your auth key set up, so you just need to select it here. Open the **Authorization** tab—select " +
"`Inherit auth from parent` from the **Type** drop-down list."
}
],
next: [
{
step: "Click **Send**."
}
]
}
});
else if (!validator.validate(apiSecret))
res.status(401).json({
welcome: welcomeMsg,
tutorial: {
title: "You got an unauthorized error response!",
intro: "🚫Unauthorized - your key needs to be an email address!",
steps: [
{
note:
"The API will only authorize your requests if your key is a valid email address."
}
],
next: [
{
step:
"Open your collection **Edit** menu and navigate to **Variables**. You should have a variable named `email_key`—make sure it's " +
"value is an email address and click **Send** again."
}
]
}
});
else if (!req.query.match_id)
res.status(400).json({
welcome: welcomeMsg,
tutorial: {
title: "Your request is missing some info! 😕",
intro: "This endpoint requires you to specify a match to update.",
steps: [
{
note:
"In **Params** add `match_id` in the **Key** column, and the `id` value from a match _you added_ to the list during this "+
"session as the **Value**. ***You can only update a match you added—in the `1. Get matches` response, find the `id` for the match "+
"you added using the `POST` request.***",
pic:
"https://assets.postman.com/postman-docs/student-expert-put-id.jpg"
}
],
next: [
{
step:
"With your parameter in place (you'll see e.g. `?match_id=abc123` added to the request address), click **Send** again."
}
]
}
});
else if (!req.body.points)
res.status(400).json({
welcome: welcomeMsg,
tutorial: {
title: "Your request is incomplete! ✋",
intro:
"This endpoint requires body data representing the updated score.",
steps: [
{
note:
"In **Body** select **raw** and choose **JSON** instead of `Text` in the drop-down list. Enter the following JSON data " +
"including the enclosing curly braces:",
raw_data: {
points: 3
},
pic:
"https://assets.postman.com/postman-docs/student-expert-score-body.jpg"
},
{
note: "_When you enter body data Postman will add the appropriate headers to the request based on what you've entered (these would "+
"otherwise need to be entered manually). Take a look in the **Code** above and to the right of the request, check the `curl` code "+
" to see the `Content-Type` header._"
}
],
next: [
{
step: "With your body data in place, click **Send** again."
}
]
}
});
else {
var updateMatch = db
.get("matches")
.find({ id: req.query.match_id })
.value();
console.log(updateMatch);
if (
updateMatch &&
apiSecret != "postman" &&
updateMatch.creator == apiSecret
) {
db.get("matches")
.find({ id: req.query.match_id })
.assign({
points: req.body.points
})
.write();
res.status(201).json({
welcome: welcomeMsg,
tutorial: {
title: "You updated a match! ✅",
intro: "Your match score was updated in the database.",
steps: [
{
note:
"Go back into the `1. Get matches` request, this time with `played` as the `status` and **Send** it again before returning here—" +
"you should see your updated match in the array! **Save** this request before continuing."
}
],
next: [
{
step:
"Next create a final request in the folder, this time naming it `4. Remove match`. Open it and set the method to `DELETE`, and " +
"the URL to `{{training_api}}/match/:match_id`."
},
{
step:
"This request includes a path parameter with `/:match_id` at the end of the request address—open **Params** and as the value " +
"for the `match_id` parameter, enter the `id` of a match _you added_ during this session when you sent the `POST` request. "+
"Copy the `id` from the response in the `1. Get matches` request like you did for the `PUT` request then click **Send**."
}
]
}
});
} else {
res.status(400).json({
welcome: welcomeMsg,
tutorial: {
title: "Your request is invalid! ⛔",
intro:
"You can only update matches you added using the `POST` method during the current session (and that haven't been deleted).",
steps: [
{
note:
"In **Params** add `match_id` in the **Key** column, and the `id` values from a match _you added_ to the list as the " +
"**Value**. ***You can only update a match you added.***"
}
],
next: [
{
step:
"With the ID parameter for a match _you added_ during this session in place, click **Send** again."
}
]
}
});
}
}
});
//delete match
app.delete("/match/:match_id", function(req, res) {
const apiSecret = req.get("match_key");
var newDate = new Date();
db.get("calls")
.push({
when: newDate.toDateString() + " " + newDate.toTimeString(),
where: "DEL /match",
what: req.params.match_id + " " + apiSecret
})
.write();
if (!apiSecret)
res.status(401).json({
welcome: welcomeMsg,
tutorial: {
title: "Oops - You got an unauthorized error response! 🚫",
intro:
"You will need to authorize your request just as you did in the `POST` and `PUT` requests.",
steps: [
{
note:
"You already have your auth key set up, so you just need to select it here. Open the **Authorization** tab—select " +
"`Inherit auth from parent` from the **Type** drop-down list."
}
],
next: [
{
step: "Click **Send**."
}
]
}
});
else if (!validator.validate(apiSecret))
res.status(401).json({
welcome: welcomeMsg,
tutorial: {
title: "You got an unauthorized error response!",
intro: "🚫Unauthorized - your key needs to be an email address!",
steps: [
{
note:
"The API will only authorize your requests if your key is a valid email address."
}
],
next: [
{
step:
"Open your collection **Edit** menu and navigate to **Variables**. You should have a variable named `email_key`—make sure it's " +
"value is an email address and click **Send** again."
}
]
}
});
else {
//check the record matches the user id
var match = db
.get("matches")
.find({ id: req.params.match_id })
.value();
if (match && apiSecret != "postman" && match.creator == apiSecret) {
db.get("matches")
.remove({ id: req.params.match_id })
.write();
res.status(200).json({
welcome: welcomeMsg,
tutorial: {
title: "You deleted a match! 🏆",
intro: "Your match was removed from the database.",
steps: [
{
note:
"Go back into the first request you opened `Get matches` and **Send** it again before returning here _making sure you use "+
"`played` as the `status` param, since you updated the score and the match is now classed as played—" +
"you should see that your deleted match is no longer in the array! **Save** this request before you continue."
}
],
next: [
{
step:
"🎊🎉 You completed the first part of Postman Student Expert training! Next we're going to jump into the `2. Scripting and " +
"Collection Runs` folder—open the folder, open the first request, and hit **Send**! 🚀"
}
]
}
});
} else {
res.status(400).json({
welcome: welcomeMsg,
tutorial: {
title: "Your request is invalid! ⛔",
intro:
"You can only remove matches you added using the `POST` method during the current session (and that haven't been deleted yet).",
steps: [
{
note:
"In **Params** add `match_id` in the **Key** column, and the `id` values from a match _you added_ to the match list as the " +
"**Value**. ***You can only remove a match you added.***"
}
],
next: [
{
step:
"With the ID parameter for a match _you added_ during this session in place, click **Send** again."
}
]
}
});
}
}
});
//delete match missing path param
app.delete("/match", function(req, res) {
const apiSecret = req.get("match_key");
var newDate = new Date();
db.get("calls")
.push({
when: newDate.toDateString() + " " + newDate.toTimeString(),
where: "DEL /match",
what: req.params.match_id + " " + apiSecret
})
.write();
if (!apiSecret)
res.status(401).json({
welcome: welcomeMsg,
tutorial: {
title: "Oops - You got an unauthorized error response! 🚫",
intro:
"You will need to authorize your request just as you did in the `POST` and `PUT` requests.",
steps: [
{
note:
"You already have your auth key set up, so you just need to select it here. Open the **Authorization** tab—select " +
"`Inherit auth from parent` from the **Type** drop-down list."
}
],
next: [
{
step: "Click **Send**."
}
]
}
});
else {
res.status(400).json({
welcome: welcomeMsg,
tutorial: {
title: "Your request is invalid! ⛔",
intro:
"You can only remove matches you added using the `POST` method during the current session (and that haven't been deleted yet).",
steps: [
{
note:
"In **Params**, for the `match_id` path variable add an `id` value from a match _you added_ to the match list" +
" ***You can only remove a match you added.***"
}
],
next: [
{
step:
"With the ID parameter for a match _you added_ during this session in place, click **Send** again."
}
]
}
});
}
});
// removes entries from users and populates it with default users
app.get("/reset", (req, res) => {
const apiSecret = req.get("admin_key");
if (!apiSecret || apiSecret !== process.env.SECRET) {
res.status(401).json(unauthorizedMsg);
} else {
// removes all entries from the collection
db.get("matches")
.remove()
.write();
console.log("Database cleared");
// default users inserted in the database
var matches = [
{
id: shortid.generate(),
creator: "postman",
matchType: "League Cup Semi Final",
opposition: "United",
date:
"Wed Mar 24 2021 14: 00: 04 GMT+0000 (Coordinated Universal Time)",
points: -1
},
{
id: shortid.generate(),
creator: "postman",
matchType: "League Cup Quarter Final",
opposition: "City",
date:
"Thu Jan 30 2020 20: 50: 46 GMT+0000 (Coordinated Universal Time)",
points: 3
},
{
id: shortid.generate(),
creator: "postman",
matchType: "Friendly",
opposition: "Athletic",
date:
"Wed Jan 13 2021 23: 01: 26 GMT+0000 (Coordinated Universal Time)",
points: -1
}
];
matches.forEach(match => {
db.get("matches")
.push({
id: match.id,
creator: match.creator,
matchType: match.matchType,
opposition: match.opposition,
date: match.date,
points: match.points
})
.write();
});
console.log("Default matches added");
res.status(200).json({
welcome: welcomeMsg,
tutorial: {
title: "Database reset",
intro: "You reset the DB."
}
});
}
});
// removes all entries from the collection
app.get("/clear", (req, res) => {
const apiSecret = req.get("admin_key");
if (!apiSecret || apiSecret !== process.env.SECRET) {
res.status(401).json(unauthorizedMsg);
} else {
// removes all entries from the collection
db.get("matches")
.remove()