Compare commits
664 Commits
chore/add-
...
chore/patc
| Author | SHA1 | Date | |
|---|---|---|---|
| 457722a79c | |||
| 5cd2e0cc59 | |||
| 12951c96cb | |||
| da1a57ba70 | |||
| b1420cfa7e | |||
| ecc9cdd747 | |||
| 471121aa0f | |||
| f3cc9ec4f5 | |||
| 4e35498be7 | |||
| 91bdb7d0e3 | |||
| 298bf229f8 | |||
| 19cdbec42b | |||
| 8d2dd60cfb | |||
| ee10daf957 | |||
| 715bef163c | |||
| 6c199e38a8 | |||
| 413443a162 | |||
| 8c341e91e0 | |||
| 712e311006 | |||
| c2f1a67a70 | |||
| f34f78aaea | |||
| 37fbc3ef45 | |||
| ddab9b96ff | |||
| 22322e5f0a | |||
| a9db9b5d5c | |||
| 645fe1055b | |||
| b202189ad6 | |||
| 1d98e8450e | |||
| fb01406a29 | |||
| 2ff71b0dd1 | |||
| dbcc882a18 | |||
| 545eaef74a | |||
| b8c3f17510 | |||
| 83671e2b22 | |||
| c8c5aa28c6 | |||
| 78cf60af4a | |||
| 4ffdd35b21 | |||
| 8d9ff3ac62 | |||
| 47708d050e | |||
| f334054b5e | |||
| 34b2ab05d4 | |||
| 0798773bcb | |||
| a2f76703ea | |||
| 0af54cd48f | |||
| 1dfdfeff1e | |||
| 1df69b3a73 | |||
| 5f3ca479aa | |||
| e1a389101f | |||
| 8621f10721 | |||
| f8e7670b3f | |||
| 397eb2b588 | |||
| b2ebd3df9c | |||
| f06e778b80 | |||
| 1511b3c118 | |||
| f76126c951 | |||
| 4523badea9 | |||
| 05fc03c032 | |||
| a89d3c7ae3 | |||
| 6278d695fa | |||
| b74a0d5d64 | |||
| 2df8f389b3 | |||
| f9ed8f16ac | |||
| d6ad90ee7a | |||
| 0cf2a4d2e7 | |||
| 2fbc13202d | |||
| bf6a2e4667 | |||
| 91584fc2ab | |||
| 42c71815e6 | |||
| e4151ed914 | |||
| f95263eec8 | |||
| b5690d8983 | |||
| 076f1fd1e4 | |||
| 71ac18cb8d | |||
| 3f267be154 | |||
| d302e8a2cb | |||
| 7463cb27f1 | |||
| 1866224b5b | |||
| 4096c0ce44 | |||
| 97feec6d3f | |||
| e03e962ab9 | |||
| 6a31609960 | |||
| 7c5aeda4a9 | |||
| ac81806b26 | |||
| 88a393c1ad | |||
| 5e8a3c84a6 | |||
| 4b37f3a121 | |||
| e8f4e7b9ee | |||
| 9af50ddfe9 | |||
| b9fefcc6a9 | |||
| 04e8354e05 | |||
| bc7ba7d507 | |||
| 6cf61d1cdb | |||
| 7497c1d004 | |||
| a3bfa4894e | |||
| 992a2b6149 | |||
| 5b1c5897fc | |||
| c6f8e5642e | |||
| dac22da0b5 | |||
| 2854912e07 | |||
| 1d366bd63d | |||
| fd59f6cbd9 | |||
| 90041555a9 | |||
| 747477cff4 | |||
| 5eb40ff8a5 | |||
| 15315f826e | |||
| 42cd34e755 | |||
| 57d0171d68 | |||
| 6df4678acc | |||
| 75537a9c3a | |||
| 7a0e303080 | |||
| e05519f651 | |||
| 99999450b5 | |||
| 01c55d52ec | |||
| b6b79e1345 | |||
| 13bfc853e3 | |||
| e0b00d1887 | |||
| 83e3414c8e | |||
| ea943206c0 | |||
| cb23379723 | |||
| 7ac8232878 | |||
| e707c9cfd8 | |||
| 809c0b9270 | |||
| c43201b867 | |||
| 53e120cd1e | |||
| 1783d5f6f7 | |||
| 41bea7b693 | |||
| 09f5fa55df | |||
| 589f630f23 | |||
| 5bcb1b3ccd | |||
| fb3be46ef2 | |||
| ca5c7c618a | |||
| 20c97de94d | |||
| e6793572bf | |||
| 4481496fda | |||
| c9cbde7a78 | |||
| a3854aab6d | |||
| 864097154e | |||
| 7a0937c04e | |||
| ef20117f3c | |||
| 91517669f0 | |||
| d92db84738 | |||
| bd1ae07662 | |||
| c946647483 | |||
| 584dd44aad | |||
| cba91dae55 | |||
| 2a80a049bd | |||
| 63ed267ded | |||
| 321631e6c9 | |||
| b535868897 | |||
| 8ed23544c5 | |||
| 4b4715cdb2 | |||
| 72f596821a | |||
| e29e772f6b | |||
| 7300a808a7 | |||
| 9a959d388f | |||
| 91ac397c75 | |||
| 4db517d4c0 | |||
| a2f074b150 | |||
| 9040ed7175 | |||
| 415b461308 | |||
| 33b0de44fb | |||
| 513c8bb127 | |||
| dc50f98a6d | |||
| 67a4b3fc8e | |||
| 155ab2b4d2 | |||
| 5ed15ee534 | |||
| 7ed780a459 | |||
| 9268ad5181 | |||
| 7d886975b9 | |||
| db263122a1 | |||
| 74a55b3f57 | |||
| 9a2b2f65b9 | |||
| c244a4b037 | |||
| e7b5f034f3 | |||
| 529f4e5869 | |||
| ca14fa6939 | |||
| 4830a449a1 | |||
| f49113e67b | |||
| 72b77c3b60 | |||
| 051f6c12e7 | |||
| 6901f6d45b | |||
| 5a183b632c | |||
| 07ccd05734 | |||
| 2c3d0a9fd4 | |||
| 8438d44ac3 | |||
| 9856719e38 | |||
| 8b8aae3ff9 | |||
| 627cb87d34 | |||
| 125081f40b | |||
| 5b9f0b9dea | |||
| 798350caed | |||
| eb8730de2a | |||
| 3b5a554b2f | |||
| 07b739cdde | |||
| eeb09dca5b | |||
| 7063f79647 | |||
| 33927f940f | |||
| b745d58ce0 | |||
| 14fbdc7408 | |||
| b7299b8359 | |||
| 5614fcae97 | |||
| 0fd8de13f9 | |||
| 6444251649 | |||
| 321e7a7fa9 | |||
| 883dc9ef6e | |||
| b737cd0fa5 | |||
| 2f46a0b07c | |||
| cc03803a3c | |||
| e78982538e | |||
| ee7b5eefda | |||
| 52a0133107 | |||
| 09ee17874d | |||
| 0a5a71d78f | |||
| 182587596c | |||
| 8ee1f1522e | |||
| ed037cf2d2 | |||
| 3302822bf8 | |||
| a76601d8cf | |||
| a543f37f77 | |||
| 5486046c24 | |||
| de3519f120 | |||
| e7488ee739 | |||
| ba700cb698 | |||
| 86710657df | |||
| d27b36a969 | |||
| 5db4a82535 | |||
| d1b60772d8 | |||
| f406e3e01d | |||
| 7c359dd775 | |||
| 5f982fe182 | |||
| df657a02f3 | |||
| b9d5f7b3df | |||
| 7f453157ee | |||
| 53632fe470 | |||
| 19336ce6ec | |||
| 868a9f3b1d | |||
| ca2a66509b | |||
| 8b5d80a9d6 | |||
| 2b04ca01a9 | |||
| 220b402b3b | |||
| db506e8b1f | |||
| 731ac4bafc | |||
| 4fbc30a264 | |||
| 18be03bfa6 | |||
| 4758d566da | |||
| 8fb296027d | |||
| 95fa610d77 | |||
| 6759bba2ce | |||
| 81272e94b1 | |||
| 1f252ee468 | |||
| ab29b08337 | |||
| 6400929eb6 | |||
| eca2ffe8ee | |||
| 28890ef8c4 | |||
| 721b66e6c1 | |||
| aae24d9920 | |||
| 2db983ef53 | |||
| f6f71526d7 | |||
| 2e5cb7e313 | |||
| f74376c8ed | |||
| 31e9c78ebd | |||
| 4b77a89ac2 | |||
| 06d2a7bb27 | |||
| 075b35e7ad | |||
| 9dcc17b687 | |||
| b068a69163 | |||
| a7c33c9479 | |||
| 1c7ee9fbc3 | |||
| b58babc7ea | |||
| f68dad0ca2 | |||
| b91f8ce151 | |||
| c21446b80a | |||
| ba82ce9f98 | |||
| bdb1da0bc4 | |||
| b02e2f721d | |||
| 6dae7959bf | |||
| ee4b11a308 | |||
| 570ab8a178 | |||
| 518044d860 | |||
| 563362b0b5 | |||
| d529554d84 | |||
| fe90ffe911 | |||
| f1dd8650b6 | |||
| 6e03dc7fe3 | |||
| 9969e93fc9 | |||
|
|
058b0d490f | ||
| bf06c7ed3a | |||
| b3cd399e10 | |||
| 4798af9674 | |||
| 12bdd4c631 | |||
| 95f2e6ec29 | |||
| 1cb498b150 | |||
| ba0375f582 | |||
| 44a0f56b93 | |||
| 26b1e70f5b | |||
| 7e74748139 | |||
| 02e440773a | |||
| 658222b91a | |||
| dd1a448160 | |||
| 544cab5324 | |||
| cb05d3ca03 | |||
| 2092827d37 | |||
| c9ecc18495 | |||
| a38ca3d3de | |||
| ea1150a98d | |||
| 37a67aace7 | |||
| 1624d78cb5 | |||
| a6d4b40fba | |||
| 2bace24623 | |||
| 776ffad162 | |||
| 267da3ff36 | |||
| 6f6bab7058 | |||
| c9aa2c401f | |||
| 0e3c12bebc | |||
| 50350d8c49 | |||
| 463f5cd582 | |||
| 44095e711a | |||
| 6cc20a4a6a | |||
| a0e0c19ca3 | |||
| d1a47baea6 | |||
| 16dce32887 | |||
| 49b823890f | |||
| c250e3ae5c | |||
| 2a01d007a9 | |||
| 6998ff529c | |||
| f67e3f13f5 | |||
| e25a96f704 | |||
| b6856a98a2 | |||
| 263607fc69 | |||
| 3d6dc1e7b6 | |||
| f6d8253719 | |||
| 8c810c5224 | |||
| 45df97f15c | |||
| aed005f7a7 | |||
| 726af52685 | |||
| b9810057ce | |||
| 110df5501d | |||
| dc639b1ca8 | |||
| aa7b21c4c0 | |||
| 461b1d1a59 | |||
| fe2b8b2f69 | |||
| e5c4387cff | |||
| 922fd7abb8 | |||
| b67b537a08 | |||
| e5b686f0be | |||
| 78514c5b8a | |||
| b2e6acfefa | |||
| be407fe220 | |||
| 6782654564 | |||
| 6cd7d38bfd | |||
| 0ce0c54ddd | |||
| 2741d229f9 | |||
| 51c2aedef6 | |||
| c7666c092c | |||
| f0c754908d | |||
| 4f855a8225 | |||
| b6f3e4ccde | |||
| 0076d987ca | |||
| 495a946e78 | |||
| 4f7d24acf0 | |||
| 059a9f5067 | |||
| 8e3765abfb | |||
| fe6db035f1 | |||
| 6767cc88a3 | |||
| 25f2a8c458 | |||
| 12f0a41153 | |||
| 34765a0f3b | |||
| e4ff597385 | |||
| 476b96c423 | |||
| 60256ce572 | |||
| 554898b097 | |||
| 96d4acb762 | |||
| 87dfd0dab1 | |||
| 0525ccc7e4 | |||
| 6e9478cd18 | |||
| bed2fbc7c3 | |||
| ea46115b86 | |||
| c8ea822626 | |||
| a830dadbee | |||
| 1e7082813d | |||
| d20711d53d | |||
| 2ba64a9b0d | |||
| d950156161 | |||
| 3d13bad11c | |||
| 329f21beb7 | |||
| 973867bd6d | |||
| 4b610c3ba9 | |||
| 9c414be8ce | |||
| dbb56f207d | |||
| c32dcb9610 | |||
| d95d112bf2 | |||
| f31e010828 | |||
| af57063b15 | |||
| f113dc1ec2 | |||
| 7136f9201d | |||
| 1629f79299 | |||
| 28c3e2f5f5 | |||
| 8a600565dc | |||
| 8dd2f02783 | |||
| ea4723df85 | |||
| 472b3a0b05 | |||
| bc598f0858 | |||
| 56466964c1 | |||
| 8c2fb3a52a | |||
| 95eb2c8f65 | |||
| 9ff388f2d4 | |||
| ed2b7dbe5e | |||
| 2d1e3c13d2 | |||
| 2d4bc6bdd4 | |||
| 940d172e87 | |||
| 6d762ce620 | |||
| db097b00dc | |||
| 2bc12aa794 | |||
| 95410470f6 | |||
| 5b695c7250 | |||
| 187800cf40 | |||
| d607a3742c | |||
| 4ea43ff21f | |||
| 503bb0fec7 | |||
| d584d1f58b | |||
| 5936c2b743 | |||
| a144657fa8 | |||
| 695fec1fce | |||
| 7e0c1f3539 | |||
|
|
af61bd4726 | ||
| d76740e5e7 | |||
|
|
1b6792a8c7 | ||
| 0e204af330 | |||
| fbc08838df | |||
| c6f846d109 | |||
| 50148cc2f4 | |||
| 39066b88bc | |||
| 9efd1d9289 | |||
| 372ecba952 | |||
| 3460f1becc | |||
| 998643dc04 | |||
| f34a2f27d7 | |||
| 7a5e1b8561 | |||
| a7ac9888f6 | |||
| 36359a4caa | |||
| cc6623404c | |||
| c98367f12e | |||
| bef2ce18fb | |||
| 1acd12d113 | |||
| a161a870d3 | |||
| c59ccd7f1a | |||
| a95c89c15b | |||
| ef94055133 | |||
| 02b3b77a61 | |||
| 75a4e133ed | |||
| 9c22e154be | |||
| a84cedd05a | |||
| 51d66d8886 | |||
| b0f04a9256 | |||
| b2fb430a38 | |||
| 2b28b94dbd | |||
| f2a2dd74f6 | |||
| ef94a9aa7e | |||
| a665c29745 | |||
| 3761f43909 | |||
| bda46d6808 | |||
| bba00eb067 | |||
| ae30660095 | |||
| fb58414ba3 | |||
| f007b72d94 | |||
| ead401a3b1 | |||
| 101c5ca6e0 | |||
| 7379840070 | |||
| c517d93e3a | |||
| 09be37cedb | |||
| 60b626b64f | |||
| 687fe0d826 | |||
| fab99db755 | |||
| 3a85f3da8b | |||
| 617f4dc72b | |||
| 7761e09b0e | |||
| 8ef161ae3b | |||
| f52b968d85 | |||
| 5d0916981f | |||
| de4cfaaa8d | |||
| e880830e02 | |||
| cb65cd49f3 | |||
| bef93538fb | |||
| 83cf38ed91 | |||
| 829b3f4ffd | |||
| 25f9dd62b1 | |||
| e12a9817ff | |||
| 299bcfcf18 | |||
| b442cdda21 | |||
| 892ca7ec63 | |||
| 4990e65c3e | |||
| 66642e7050 | |||
| f2a464d52d | |||
| 2dd91c9885 | |||
| 9942796f26 | |||
| 7199adf20e | |||
| 4d74027b0e | |||
| 717575e004 | |||
| 99672e749f | |||
| 96e7e0297b | |||
| 14a3738fba | |||
| 1321ff1347 | |||
| fb49577cf6 | |||
| 1f8d4bfbd4 | |||
| 50636e5582 | |||
| 07b80f2012 | |||
| 8874704acb | |||
| 9e6e20503d | |||
| 7e3305247d | |||
| 2ccdba3d11 | |||
| 20282c3cf9 | |||
| ac65e23984 | |||
| e433662f19 | |||
| 5670efb042 | |||
| 6251f0e247 | |||
| a6ceeb4dfb | |||
| 26cdab9907 | |||
| 23dc4c3f59 | |||
| 9869632a88 | |||
| 7f1bf005c1 | |||
| 83766c90c5 | |||
| a58780a37d | |||
| 619ef9a27f | |||
|
|
eaa23d635c | ||
| 049ea731a3 | |||
| d8ec54919e | |||
| 135a294e5d | |||
| 889e302912 | |||
| 891bf522ba | |||
| 024a7dd30c | |||
| 919832e86f | |||
| c0b7d99e8e | |||
| d9d11e1b31 | |||
| 217fb065cb | |||
| 371fb25faf | |||
| e8d5dbe6b3 | |||
| ad07a6be44 | |||
| 614b062b01 | |||
| bc2f90e11e | |||
| 58bb8a1c32 | |||
| f1b9fb6824 | |||
| 92537a298b | |||
| 63a215ac41 | |||
| 556906d15e | |||
| 6da782fd3d | |||
| 3b173aeb22 | |||
| 11871da802 | |||
| 11934da0af | |||
| 8794ced2dc | |||
| d8091bf148 | |||
| 5c49221783 | |||
| fdc62563b2 | |||
| ed2f2d42f3 | |||
| f5d40ebd7a | |||
| e22537d93d | |||
| 8971e3514d | |||
| e697fd89b8 | |||
| c09d35b65c | |||
| c1ec50db7b | |||
| bb77aca4ed | |||
| b4f1f1b87d | |||
| 420682dbb8 | |||
| 3ce72d79be | |||
| 19b08d1c05 | |||
| 2d4e206739 | |||
| a74a6c995a | |||
| bf1290bbc8 | |||
| d80df1de23 | |||
| ebcd35b85d | |||
|
|
9af48be746 | ||
| 6d1a85c2b4 | |||
| 4fdf60f9bf | |||
| 764f6e35f0 | |||
| b5954e251d | |||
| a880d71c87 | |||
| 5e186c643c | |||
| baa94eeef5 | |||
| da224c36ed | |||
| 2d92370254 | |||
| 6635a1a89b | |||
| a6138b37cb | |||
| 7e764502a0 | |||
| a3efae9f24 | |||
| 4351c6d454 | |||
| d3c824be68 | |||
| 4c4bd0fc4a | |||
| 2b0bef876c | |||
| fa40d15f5a | |||
| e667e89556 | |||
| 71698da173 | |||
| acc4d08716 | |||
| d7b15812f3 | |||
| 1627bc39fe | |||
| 69e2748eec | |||
| 94c15f93dd | |||
| cea7b48323 | |||
| 3a51d15e63 | |||
| 5687f7f600 | |||
| 0b9759aff1 | |||
| 8ac71090e4 | |||
| dccee459c3 | |||
| b918bf7a67 | |||
| 814f2c6584 | |||
| c79a3eac73 | |||
| 43f0ef27fc | |||
| f1f1d5c971 | |||
| d54539e65b | |||
| 588d433fa3 | |||
| 2116387203 | |||
| d730937b29 | |||
| 82a70ea04e | |||
|
|
6c31346d65 | ||
| 9048d2f1bc | |||
| 4a63929cc1 | |||
| 629fe4dddd | |||
| 403bec7c63 | |||
| d1db9b3742 | |||
| 3e4f6e5440 | |||
| 80e976752b | |||
| 6473661607 | |||
| aff82a8185 | |||
| c593fe14e1 | |||
| 602ccf8139 | |||
| b3b4b71e22 | |||
| 11ea0518fe | |||
| 0cd7c2fe47 | |||
| 179fa07d36 | |||
| b252adb5d4 | |||
| 64931e7546 | |||
| 4c8658a3d9 | |||
| 16d2d4b4ef | |||
| d357af7509 | |||
| 103ddef523 | |||
| c5c0208371 | |||
| f602aa6c2c | |||
| 18402401e3 | |||
| 339148c890 | |||
| 711caa1d15 | |||
| 90e5fa200e | |||
| 8bc71d25fe | |||
| e96316aa1e | |||
| fba021d921 | |||
| 3bdc730c95 | |||
| 69525a643d | |||
| 737a61fd41 | |||
| e9c2c8a7bc | |||
| 1e82ec2697 | |||
| 11fe22ceea | |||
| fe233dfcbd | |||
| 6172a04427 | |||
| f8ff7f9cc9 | |||
| dbbb9c0169 | |||
| 7d762f17dc | |||
| fe16bc7124 | |||
| b30e4be895 | |||
| 9dd6e945c2 | |||
| a810a2e78f | |||
| 01cbad3a73 | |||
| 047ff3a56e | |||
| ec62b0c8bf | |||
| 899b953be5 | |||
| 5957010a7f | |||
| 345d4905fe | |||
| acfc91d3c1 |
4
.dockerignore
Normal file
4
.dockerignore
Normal file
@@ -0,0 +1,4 @@
|
||||
node_modules
|
||||
npm-debug.log
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
22
.env.example
22
.env.example
@@ -1,4 +1,24 @@
|
||||
# Set to "1" for true
|
||||
APNS_IS_PRODUCTION=
|
||||
|
||||
APNS_KEY_ID=
|
||||
APNS_TEAM_ID=
|
||||
APNS_BUNDLE_ID=
|
||||
APNS_KEY_PATH=
|
||||
|
||||
# base64-encoded APNs private key
|
||||
APNS_PRIVATE_KEY=
|
||||
|
||||
# control parking data logging
|
||||
PARKING_LOGGING_INTERVAL_MS=
|
||||
PARKING_HISTORICAL_AVERAGE_MINIMUM_INTERVAL=
|
||||
PARKING_HISTORICAL_AVERAGE_MAXIMUM_TIMESPAN=
|
||||
|
||||
# control rate limiting features
|
||||
RATE_LIMITS_DISABLED=
|
||||
RATE_LIMIT_WINDOW_MS=
|
||||
RATE_LIMIT_DELAY_AFTER_REQUESTS=
|
||||
RATE_LIMIT_DELAY_MULTIPLIER_MS=
|
||||
|
||||
# Redis connection
|
||||
REDIS_URL=
|
||||
REDIS_USE_TLS=
|
||||
|
||||
12
.github/ISSUE_TEMPLATE/bug-report.md
vendored
Normal file
12
.github/ISSUE_TEMPLATE/bug-report.md
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Describe a bug within the app.
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
## Bug description
|
||||
|
||||
A clear and concise description of what the bug is, including how to reproduce it plus relevant screenshots.
|
||||
20
.github/ISSUE_TEMPLATE/enhancement.md
vendored
Normal file
20
.github/ISSUE_TEMPLATE/enhancement.md
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: Enhancement
|
||||
about: New feature or enhancement for the project.
|
||||
title: ''
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
## User stories
|
||||
|
||||
- As a user...
|
||||
|
||||
## Tasks
|
||||
|
||||
- [ ]
|
||||
|
||||
## Documentation
|
||||
|
||||
-
|
||||
16
.github/ISSUE_TEMPLATE/generic-task.md
vendored
Normal file
16
.github/ISSUE_TEMPLATE/generic-task.md
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
---
|
||||
name: Generic task
|
||||
about: Task with multiple steps.
|
||||
title: ''
|
||||
labels:
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
## Tasks
|
||||
|
||||
- [ ]
|
||||
|
||||
## Documentation
|
||||
|
||||
-
|
||||
60
.github/workflows/deploy.yml
vendored
Normal file
60
.github/workflows/deploy.yml
vendored
Normal file
@@ -0,0 +1,60 @@
|
||||
name: "Deploy to birb co."
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@v3
|
||||
|
||||
# See documentation: https://github.com/tailscale/github-action?tab=readme-ov-file
|
||||
- name: Connect to Tailscale
|
||||
uses: tailscale/github-action@v4
|
||||
with:
|
||||
oauth-client-id: ${{ secrets.TS_OAUTH_CLIENT_ID }}
|
||||
oauth-secret: ${{ secrets.TS_OAUTH_CLIENT_SECRET }}
|
||||
tags: tag:ci
|
||||
|
||||
- name: Set up SSH key
|
||||
run: |
|
||||
mkdir -p ~/.ssh
|
||||
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_ed25519
|
||||
chmod 600 ~/.ssh/id_ed25519
|
||||
ssh-keyscan ${{ vars.HOST }} >> ~/.ssh/known_hosts
|
||||
|
||||
- name: Remove directory from server
|
||||
run: |
|
||||
ssh -i ~/.ssh/id_ed25519 ${{ vars.USERNAME }}@${{ vars.HOST }} << 'EOF'
|
||||
rm -rf ~/${{ vars.DIRECTORY_NAME }}
|
||||
EOF
|
||||
|
||||
# Avoid needing to set up SSH access to GitHub for this user
|
||||
- name: Transfer repository files to server
|
||||
run: |
|
||||
scp -i ~/.ssh/id_ed25519 -r ./* ${{ vars.USERNAME }}@${{ vars.HOST }}:~/${{ vars.DIRECTORY_NAME }}
|
||||
|
||||
- name: Deploy on server with Docker
|
||||
run: |
|
||||
ssh -i ~/.ssh/id_ed25519 ${{ vars.USERNAME }}@${{ vars.HOST }} << 'EOF'
|
||||
cd ~/${{ vars.DIRECTORY_NAME }}
|
||||
export APNS_IS_PRODUCTION=${{ secrets.APNS_IS_PRODUCTION }}
|
||||
export APNS_BUNDLE_ID=${{ secrets.APNS_BUNDLE_ID }}
|
||||
export APNS_TEAM_ID=${{ secrets.APNS_TEAM_ID }}
|
||||
export APNS_KEY_ID=${{ secrets.APNS_KEY_ID }}
|
||||
export APNS_PRIVATE_KEY=${{ secrets.APNS_PRIVATE_KEY }}
|
||||
export PARKING_LOGGING_INTERVAL_MS=${{ secrets.PARKING_LOGGING_INTERVAL_MS }}
|
||||
export RATE_LIMITS_DISABLED=${{ secrets.RATE_LIMITS_DISABLED }}
|
||||
export RATE_LIMIT_WINDOW_MS=${{ secrets.RATE_LIMIT_WINDOW_MS }}
|
||||
export RATE_LIMIT_DELAY_AFTER_REQUESTS=${{ secrets.RATE_LIMIT_DELAY_AFTER_REQUESTS }}
|
||||
export RATE_LIMIT_DELAY_MULTIPLIER_MS=${{ secrets.RATE_LIMIT_DELAY_MULTIPLIER_MS }}
|
||||
export DOCKER_HOST=unix://$XDG_RUNTIME_DIR/docker.sock
|
||||
docker compose -f docker-compose.prod.yml down --remove-orphans
|
||||
docker compose -f docker-compose.prod.yml up -d --build
|
||||
EOF
|
||||
34
.github/workflows/test.yml
vendored
34
.github/workflows/test.yml
vendored
@@ -1,27 +1,31 @@
|
||||
name: Node.js Test
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [20.x]
|
||||
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
|
||||
- name: Build and test with Docker Compose
|
||||
run: docker compose run test
|
||||
|
||||
- name: Upload test coverage
|
||||
id: coverage-upload
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: 'npm'
|
||||
- run: npm run build:dev
|
||||
- run: npm run test
|
||||
name: code-coverage-report
|
||||
path: coverage
|
||||
|
||||
- name: Post comment linking to artifact
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh pr comment ${{ github.event.pull_request.number }} \
|
||||
--repo ${{ github.repository }} \
|
||||
--body "Test coverage artifact: ${{ steps.coverage-upload.outputs.artifact-url }}"
|
||||
|
||||
|
||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -20,3 +20,9 @@ yarn-error.log*
|
||||
|
||||
# Testing
|
||||
/coverage/
|
||||
|
||||
# Keys
|
||||
private/
|
||||
|
||||
# JetBrains
|
||||
.idea
|
||||
|
||||
8
.idea/.gitignore
generated
vendored
8
.idea/.gitignore
generated
vendored
@@ -1,8 +0,0 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
5
.idea/codeStyles/codeStyleConfig.xml
generated
5
.idea/codeStyles/codeStyleConfig.xml
generated
@@ -1,5 +0,0 @@
|
||||
<component name="ProjectCodeStyleConfiguration">
|
||||
<state>
|
||||
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
|
||||
</state>
|
||||
</component>
|
||||
6
.idea/inspectionProfiles/Project_Default.xml
generated
6
.idea/inspectionProfiles/Project_Default.xml
generated
@@ -1,6 +0,0 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="ExceptionCaughtLocallyJS" enabled="false" level="WARNING" enabled_by_default="false" />
|
||||
</profile>
|
||||
</component>
|
||||
8
.idea/modules.xml
generated
8
.idea/modules.xml
generated
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/project-inter-server.iml" filepath="$PROJECT_DIR$/.idea/project-inter-server.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
12
.idea/project-inter-server.iml
generated
12
.idea/project-inter-server.iml
generated
@@ -1,12 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="WEB_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<excludeFolder url="file://$MODULE_DIR$/.tmp" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/temp" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/tmp" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
6
.idea/vcs.xml
generated
6
.idea/vcs.xml
generated
@@ -1,6 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
93
CLAUDE.md
Normal file
93
CLAUDE.md
Normal file
@@ -0,0 +1,93 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code when working with code in this repository.
|
||||
|
||||
## Development Commands
|
||||
|
||||
### Core Development
|
||||
```bash
|
||||
# Start development server with hot reloading
|
||||
docker compose run dev
|
||||
|
||||
# Run comprehensive test suite
|
||||
docker compose run test
|
||||
|
||||
# Generate GraphQL TypeScript types
|
||||
npm run generate
|
||||
|
||||
# Build for development (install, codegen, tsc)
|
||||
npm run build:dev
|
||||
```
|
||||
|
||||
Only use Docker Compose for running tests, and only use `docker compose run test`
|
||||
to run tests; don't try to run tests for individual files.
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
Project Inter Server is a GraphQL-based backend for college transit tracking with real-time shuttle data, parking availability, and push notifications.
|
||||
|
||||
- InterchangeSystem: Central orchestrator for shuttles, parking, and notifications
|
||||
- Use `InterchangeSystem.build()` in production
|
||||
- Use `InterchangeSystem.buildForTesting()` in tests
|
||||
|
||||
- Repository Pattern (data access abstraction)
|
||||
- Shuttle: `UnoptimizedInMemoryShuttleRepository`
|
||||
- Parking: `InMemoryParkingRepository`
|
||||
- Notifications: `RedisNotificationRepository` (prod) / `InMemoryNotificationRepository` (test)
|
||||
|
||||
- Data Loaders (external API integration)
|
||||
- `ApiBasedShuttleRepositoryLoader` – Passio GO! API
|
||||
- `ChapmanApiBasedParkingRepositoryLoader` – Parking data
|
||||
- `TimedApiBasedRepositoryLoader` – Periodic refresh wrapper
|
||||
|
||||
- Notification System
|
||||
- `ETANotificationScheduler` – Shuttle arrival notifications
|
||||
- `AppleNotificationSender` – APNS integration
|
||||
|
||||
## GraphQL
|
||||
- Schema definition: `schema.graphqls`
|
||||
- Generated types: `src/generated/`
|
||||
- Resolvers: `src/resolvers/`
|
||||
- Resolver merge: `src/MergedResolvers.ts`
|
||||
|
||||
## Directory Structure
|
||||
- `src/entities/` – Core business logic
|
||||
- `src/repositories/` – Data access layer
|
||||
- `src/loaders/` – External API integrations
|
||||
- `src/notifications/` – Push notification system
|
||||
- `src/resolvers/` – GraphQL resolvers and tests
|
||||
- `testHelpers/` – Test utilities and mock data
|
||||
|
||||
## Docker Services
|
||||
- `dev` – Development server with hot reload
|
||||
- `test` – Unit/integration tests
|
||||
- `redis` – Persistent Redis
|
||||
- `redis-no-persistence` – Ephemeral Redis for tests
|
||||
|
||||
## Testing Patterns
|
||||
- Prefer `buildForTesting()` to construct systems in tests.
|
||||
- Mock external APIs using JSON snapshots under `testHelpers/jsonSnapshots`.
|
||||
- Use in-memory repositories for speed where possible.
|
||||
- When adding features that affect API output, add focused resolver tests in the corresponding `src/resolvers/__tests__` file.
|
||||
- Separate unit tests from integration tests where practical to keep feedback fast and failures well-scoped.
|
||||
|
||||
## Development Guidelines
|
||||
|
||||
### General Guidelines
|
||||
- Use test-driven development where possible. Write tests before implementation and run them before and after changes.
|
||||
- Use Docker Compose for tests. Run `docker compose run test` so you can see full output.
|
||||
|
||||
### Git Workflow
|
||||
- Name pull requests after their branch name.
|
||||
|
||||
### Code Style
|
||||
- Prefer arrow functions, especially within classes.
|
||||
- Keep changes minimal and focused; avoid unrelated refactors. Mention incidental issues separately.
|
||||
- Respect existing interfaces and types; use non-destructive edits.
|
||||
|
||||
### Agent Tips
|
||||
- Write or update tests alongside changes; validate with `docker compose run test`.
|
||||
- When touching GraphQL resolvers, co-locate new tests in `src/resolvers/__tests__`.
|
||||
|
||||
## Multi-tenant Support
|
||||
Currently supports Chapman University (Passio System ID: `263`). Each university system uses isolated repositories and configuration. New systems should be added via `InterchangeSystem` configuration and appropriate loaders.
|
||||
4
Caddyfile
Normal file
4
Caddyfile
Normal file
@@ -0,0 +1,4 @@
|
||||
interchange-api.bchen.dev {
|
||||
reverse_proxy app:4000
|
||||
}
|
||||
|
||||
4
Dockerfile
Normal file
4
Dockerfile
Normal file
@@ -0,0 +1,4 @@
|
||||
FROM node:22-alpine
|
||||
WORKDIR /usr/src/app
|
||||
COPY . .
|
||||
EXPOSE 4000
|
||||
22
README.md
22
README.md
@@ -1,17 +1,19 @@
|
||||
# Interchange Node.js Server
|
||||
# Interchange Server
|
||||
|
||||
This is the server codebase for Interchange, an app for college
|
||||
transit.
|
||||
This is the server codebase for Interchange, an app for college transit.
|
||||
|
||||
## Setup
|
||||
|
||||
You'll need Node.js 20.x installed to run this project.
|
||||
Clone this repository and run the following:
|
||||
You'll need Docker + Compose installed to run this project.
|
||||
Clone this repository and run one of the following:
|
||||
|
||||
```bash
|
||||
$ npm start:dev
|
||||
# run the standard Node development server and Redis
|
||||
$ docker compose run dev
|
||||
|
||||
# run with unit/server integration tests
|
||||
$ docker compose run test
|
||||
|
||||
# run with test data suitable for app integration tests
|
||||
$ docker compose run app-integration-tests
|
||||
```
|
||||
|
||||
This will run `npm install`, generate GraphQL type definitions,
|
||||
and start the server in developer mode.
|
||||
|
||||
|
||||
52
docker-compose.prod.yml
Normal file
52
docker-compose.prod.yml
Normal file
@@ -0,0 +1,52 @@
|
||||
# self hosted server setup using Caddy
|
||||
|
||||
x-common-environment: &common-server-environment
|
||||
APNS_IS_PRODUCTION: ${APNS_IS_PRODUCTION}
|
||||
APNS_BUNDLE_ID: ${APNS_BUNDLE_ID}
|
||||
APNS_TEAM_ID: ${APNS_TEAM_ID}
|
||||
APNS_KEY_ID: ${APNS_KEY_ID}
|
||||
APNS_PRIVATE_KEY: ${APNS_PRIVATE_KEY}
|
||||
PARKING_LOGGING_INTERVAL_MS: ${PARKING_LOGGING_INTERVAL_MS}
|
||||
REDIS_URL: redis://redis:6379
|
||||
REDIS_USE_TLS: 0
|
||||
RATE_LIMITS_DISABLED: ${RATE_LIMITS_DISABLED}
|
||||
RATE_LIMIT_WINDOW_MS: ${RATE_LIMIT_WINDOW_MS}
|
||||
RATE_LIMIT_DELAY_AFTER_REQUESTS: ${RATE_LIMIT_DELAY_AFTER_REQUESTS}
|
||||
RATE_LIMIT_DELAY_MULTIPLIER_MS: ${RATE_LIMIT_DELAY_MULTIPLIER_MS}
|
||||
|
||||
services:
|
||||
app:
|
||||
build: .
|
||||
command: npm run start
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- redis
|
||||
environment:
|
||||
<<: *common-server-environment
|
||||
NODE_ENV: production
|
||||
|
||||
redis:
|
||||
image: redis/redis-stack:7.2.0-v17
|
||||
container_name: redis-timeseries
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
- ./redis-stack.conf:/redis-stack.conf
|
||||
command: redis-stack-server /redis-stack.conf
|
||||
|
||||
caddy:
|
||||
image: caddy:2-alpine
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
- "443:443/udp"
|
||||
volumes:
|
||||
- ./Caddyfile:/etc/caddy/Caddyfile
|
||||
- caddy_data:/data
|
||||
- caddy_config:/config
|
||||
|
||||
volumes:
|
||||
redis_data:
|
||||
caddy_data:
|
||||
caddy_config:
|
||||
64
docker-compose.yml
Normal file
64
docker-compose.yml
Normal file
@@ -0,0 +1,64 @@
|
||||
# Note that .env file will automatically populate
|
||||
# variables in this file.
|
||||
# If these variables are also set on the host system,
|
||||
# those will be used over the .env file.
|
||||
# See https://vsupalov.com/docker-arg-env-variable-guide/
|
||||
|
||||
x-common-environment: &common-server-environment
|
||||
APNS_IS_PRODUCTION: ${APNS_IS_PRODUCTION}
|
||||
APNS_BUNDLE_ID: ${APNS_BUNDLE_ID}
|
||||
APNS_TEAM_ID: ${APNS_TEAM_ID}
|
||||
APNS_KEY_ID: ${APNS_KEY_ID}
|
||||
APNS_PRIVATE_KEY: ${APNS_PRIVATE_KEY}
|
||||
PARKING_LOGGING_INTERVAL_MS: ${PARKING_LOGGING_INTERVAL_MS}
|
||||
REDIS_URL: redis://redis:6379
|
||||
REDIS_USE_TLS: 0
|
||||
RATE_LIMITS_DISABLED: ${RATE_LIMITS_DISABLED}
|
||||
RATE_LIMIT_WINDOW_MS: ${RATE_LIMIT_WINDOW_MS}
|
||||
RATE_LIMIT_DELAY_AFTER_REQUESTS: ${RATE_LIMIT_DELAY_AFTER_REQUESTS}
|
||||
RATE_LIMIT_DELAY_MULTIPLIER_MS: ${RATE_LIMIT_DELAY_MULTIPLIER_MS}
|
||||
|
||||
services:
|
||||
dev:
|
||||
build: .
|
||||
command: npm run start:dev
|
||||
ports:
|
||||
- "4000:4000"
|
||||
depends_on:
|
||||
- redis
|
||||
environment:
|
||||
<<: *common-server-environment
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
|
||||
test:
|
||||
build: .
|
||||
command: npm run test
|
||||
depends_on:
|
||||
- redis-no-persistence
|
||||
environment:
|
||||
REDIS_URL: redis://redis-no-persistence:6379
|
||||
RATE_LIMITS_DISABLED: 1
|
||||
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
|
||||
redis:
|
||||
image: redis/redis-stack:7.2.0-v17
|
||||
container_name: redis-timeseries
|
||||
ports:
|
||||
- "6379:6379"
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
- ./redis-stack.conf:/redis-stack.conf
|
||||
command: redis-stack-server /redis-stack.conf
|
||||
|
||||
redis-no-persistence:
|
||||
image: redis/redis-stack:7.2.0-v17
|
||||
container_name: redis-timeseries-no-persistence
|
||||
ports:
|
||||
- "6379:6379"
|
||||
|
||||
volumes:
|
||||
redis_data: # Add this volume definition
|
||||
|
||||
@@ -110,7 +110,7 @@ const config = {
|
||||
// reporters: undefined,
|
||||
|
||||
// Automatically reset mock state before every test
|
||||
// resetMocks: false,
|
||||
resetMocks: true,
|
||||
|
||||
// Reset the module registry before running each individual test
|
||||
// resetModules: false,
|
||||
@@ -119,7 +119,7 @@ const config = {
|
||||
// resolver: undefined,
|
||||
|
||||
// Automatically restore mock state and implementation before every test
|
||||
// restoreMocks: false,
|
||||
restoreMocks: true,
|
||||
|
||||
// The root directory that Jest should scan for tests and modules within
|
||||
// rootDir: undefined,
|
||||
|
||||
4182
package-lock.json
generated
4182
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
22
package.json
22
package.json
@@ -4,28 +4,38 @@
|
||||
"description": "",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"build:dev": "npm install --include=dev && npm run generate && tsc",
|
||||
"build": "npm install --include=dev && npm run generate && tsc && npm prune --omit=dev",
|
||||
"build:dev": "npm install --include=dev && npm run generate && tsc --project tsconfig.build.json",
|
||||
"build": "npm install --include=dev && npm run generate && tsc --project tsconfig.build.json && npm prune --omit=dev",
|
||||
"start:dev": "npm run build:dev && node ./dist/index.js",
|
||||
"start": "npm run build && node ./dist/index.js",
|
||||
"generate": "graphql-codegen --config codegen.ts",
|
||||
"test": "jest"
|
||||
"test": "npm run build:dev && jest --runInBand"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@graphql-codegen/cli": "5.0.3",
|
||||
"@graphql-codegen/typescript": "4.1.2",
|
||||
"@graphql-codegen/typescript-resolvers": "4.4.1",
|
||||
"@jest/globals": "^29.7.0",
|
||||
"@types/express": "^5.0.3",
|
||||
"@types/jsonwebtoken": "^9.0.8",
|
||||
"@types/node": "^22.10.2",
|
||||
"@types/redis": "^4.0.11",
|
||||
"jest": "^29.7.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"typescript": "^5.7.2",
|
||||
"@types/jsonwebtoken": "^9.0.8"
|
||||
"typescript": "^5.7.2"
|
||||
},
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@apollo/server": "^4.11.2",
|
||||
"@as-integrations/express5": "^1.1.2",
|
||||
"express": "^5.1.0",
|
||||
"express-rate-limit": "^8.0.1",
|
||||
"express-slow-down": "^3.0.0",
|
||||
"graphql": "^16.10.0",
|
||||
"jsonwebtoken": "^9.0.2"
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"redis": "^4.7.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.15.0"
|
||||
}
|
||||
}
|
||||
|
||||
28
redis-stack.conf
Normal file
28
redis-stack.conf
Normal file
@@ -0,0 +1,28 @@
|
||||
# See https://raw.githubusercontent.com/redis/redis/unstable/redis.conf
|
||||
# for a full example
|
||||
|
||||
############################## APPEND ONLY MODE ###############################
|
||||
|
||||
# By default Redis asynchronously dumps the dataset on disk. This mode is
|
||||
# good enough in many applications, but an issue with the Redis process or
|
||||
# a power outage may result into a few minutes of writes lost (depending on
|
||||
# the configured save points).
|
||||
#
|
||||
# The Append Only File is an alternative persistence mode that provides
|
||||
# much better durability. For instance using the default data fsync policy
|
||||
# (see later in the config file) Redis can lose just one second of writes in a
|
||||
# dramatic event like a server power outage, or a single write if something
|
||||
# wrong with the Redis process itself happens, but the operating system is
|
||||
# still running correctly.
|
||||
#
|
||||
# AOF and RDB persistence can be enabled at the same time without problems.
|
||||
# If the AOF is enabled on startup Redis will load the AOF, that is the file
|
||||
# with the better durability guarantees.
|
||||
#
|
||||
# Note that changing this value in a config file of an existing database and
|
||||
# restarting the server can lead to data loss. A conversion needs to be done
|
||||
# by setting it via CONFIG command on a live server first.
|
||||
#
|
||||
# Please check https://redis.io/docs/latest/operate/oss_and_stack/management/persistence/ for more information.
|
||||
|
||||
appendonly yes
|
||||
@@ -1,8 +1,8 @@
|
||||
type Query {
|
||||
systems: [System!]!
|
||||
system(id: ID): System
|
||||
}
|
||||
scalar DateTime
|
||||
|
||||
# The Interchange system schema.
|
||||
# Note how Passio ID and parking ID are abstracted away
|
||||
# from the endpoints.
|
||||
type System {
|
||||
id: ID!
|
||||
name: String!
|
||||
@@ -12,15 +12,51 @@ type System {
|
||||
stop(id: ID): Stop
|
||||
shuttles: [Shuttle!]
|
||||
shuttle(id: ID): Shuttle
|
||||
|
||||
parkingSystem: ParkingSystem
|
||||
}
|
||||
|
||||
type ParkingSystem {
|
||||
systemId: ID!
|
||||
parkingStructures: [ParkingStructure!]
|
||||
parkingStructure(id: ID): ParkingStructure
|
||||
}
|
||||
|
||||
type ParkingStructure {
|
||||
id: ID!
|
||||
name: String!
|
||||
capacity: Int!
|
||||
spotsAvailable: Int!
|
||||
coordinates: Coordinates!
|
||||
address: String!
|
||||
updatedTime: DateTime
|
||||
systemId: ID!
|
||||
|
||||
historicalAverages(input: HistoricalParkingAverageQueryInput): [HistoricalParkingAverageQueryResult!]
|
||||
}
|
||||
|
||||
type HistoricalParkingAverageQueryResult {
|
||||
from: DateTime!
|
||||
to: DateTime!
|
||||
averageSpotsAvailable: Float!
|
||||
}
|
||||
|
||||
input HistoricalParkingAverageQueryInput {
|
||||
from: DateTime!
|
||||
to: DateTime!
|
||||
intervalMs: Int!
|
||||
}
|
||||
|
||||
type Route {
|
||||
name: String!
|
||||
id: ID!
|
||||
systemId: ID!
|
||||
orderedStop(forStopId: ID): OrderedStop
|
||||
orderedStops: [OrderedStop]
|
||||
shuttles: [Shuttle!]
|
||||
polylineCoordinates: [Coordinates!]!
|
||||
color: String!
|
||||
updatedTime: DateTime
|
||||
}
|
||||
|
||||
type OrderedStop {
|
||||
@@ -30,14 +66,18 @@ type OrderedStop {
|
||||
routeId: ID!
|
||||
stop: Stop
|
||||
stopId: ID!
|
||||
systemId: ID!
|
||||
updatedTime: DateTime
|
||||
}
|
||||
|
||||
type Stop {
|
||||
id: ID!
|
||||
systemId: ID!
|
||||
name: String!
|
||||
coordinates: Coordinates!
|
||||
etas: [ETA!]
|
||||
orderedStops: [OrderedStop!]
|
||||
updatedTime: DateTime
|
||||
}
|
||||
|
||||
type Coordinates {
|
||||
@@ -51,14 +91,57 @@ type ETA {
|
||||
shuttle: Shuttle
|
||||
shuttleId: ID!
|
||||
secondsRemaining: Float!
|
||||
systemId: ID!
|
||||
updatedTime: DateTime
|
||||
}
|
||||
|
||||
type Shuttle {
|
||||
name: String!
|
||||
systemId: ID!
|
||||
id: ID!,
|
||||
coordinates: Coordinates!
|
||||
route: Route
|
||||
routeId: ID!
|
||||
etas: [ETA!]
|
||||
eta(forStopId: ID): ETA
|
||||
orientationInDegrees: Float!
|
||||
updatedTime: DateTime
|
||||
}
|
||||
|
||||
# Queries
|
||||
type Query {
|
||||
systems: [System!]!
|
||||
system(id: ID): System
|
||||
|
||||
isNotificationScheduled(input: NotificationInput!): Boolean
|
||||
secondsThresholdForNotification(input: NotificationInput!): Int
|
||||
|
||||
schemaMinVersion: Int!
|
||||
schemaCurrentVersion: Int!
|
||||
}
|
||||
|
||||
# Mutations
|
||||
type Mutation {
|
||||
scheduleNotification(input: NotificationInput!): NotificationResponse!
|
||||
cancelNotification(input: NotificationInput!): NotificationResponse!
|
||||
}
|
||||
|
||||
input NotificationInput {
|
||||
deviceId: ID!
|
||||
shuttleId: ID!
|
||||
stopId: ID!
|
||||
secondsThreshold: Int
|
||||
}
|
||||
|
||||
type NotificationResponse {
|
||||
success: Boolean!
|
||||
message: String!
|
||||
data: Notification
|
||||
}
|
||||
|
||||
type Notification {
|
||||
deviceId: ID!
|
||||
shuttleId: ID!
|
||||
stopId: ID!
|
||||
secondsThreshold: Int
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Coordinates, Eta, OrderedStop, Resolvers } from "./generated/graphql";
|
||||
import { Resolvers } from "./generated/graphql";
|
||||
import { ServerContext } from "./ServerContext";
|
||||
import { QueryResolvers } from "./resolvers/QueryResolvers";
|
||||
import { SystemResolvers } from "./resolvers/SystemResolvers";
|
||||
@@ -7,13 +7,21 @@ import { OrderedStopResolvers } from "./resolvers/OrderedStopResolvers";
|
||||
import { StopResolvers } from "./resolvers/StopResolvers";
|
||||
import { ShuttleResolvers } from "./resolvers/ShuttleResolvers";
|
||||
import { RouteResolvers } from "./resolvers/RouteResolvers";
|
||||
import { MutationResolvers } from "./resolvers/MutationResolvers";
|
||||
import { ParkingSystemResolvers } from "./resolvers/ParkingSystemResolvers";
|
||||
import { DateTime } from "./scalars/DateTime";
|
||||
import { ParkingStructureResolvers } from "./resolvers/ParkingStructureResolvers";
|
||||
|
||||
export const MergedResolvers: Resolvers<ServerContext> = {
|
||||
...QueryResolvers,
|
||||
...ParkingSystemResolvers,
|
||||
...SystemResolvers,
|
||||
...RouteResolvers,
|
||||
...ShuttleResolvers,
|
||||
...StopResolvers,
|
||||
...OrderedStopResolvers,
|
||||
...EtaResolvers,
|
||||
};
|
||||
...MutationResolvers,
|
||||
...ParkingStructureResolvers,
|
||||
DateTime: DateTime,
|
||||
};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { GetterRepository } from "./repositories/GetterRepository";
|
||||
import { InterchangeSystem } from "./entities/InterchangeSystem";
|
||||
|
||||
export interface ServerContext {
|
||||
repository: GetterRepository;
|
||||
}
|
||||
systems: InterchangeSystem[];
|
||||
findSystemById: (id: string) => InterchangeSystem | null;
|
||||
}
|
||||
|
||||
11
src/__mocks__/environment.ts
Normal file
11
src/__mocks__/environment.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
export const PARKING_LOGGING_INTERVAL_MS = 10000;
|
||||
|
||||
export const PARKING_HISTORICAL_AVERAGE_MINIMUM_INTERVAL = 1000;
|
||||
|
||||
export const PARKING_HISTORICAL_AVERAGE_MAXIMUM_TIMESPAN = 60000 * 60 * 24;
|
||||
|
||||
export const RATE_LIMITS_DISABLED = true;
|
||||
export const RATE_LIMIT_WINDOW_MS = 10000;
|
||||
export const RATE_LIMIT_DELAY_AFTER_REQUESTS = 10000;
|
||||
export const RATE_LIMIT_DELAY_MULTIPLIER_MS = 1000;
|
||||
|
||||
285
src/entities/InterchangeSystem.ts
Normal file
285
src/entities/InterchangeSystem.ts
Normal file
@@ -0,0 +1,285 @@
|
||||
import { ETANotificationScheduler } from "../notifications/schedulers/ETANotificationScheduler";
|
||||
import { TimedApiBasedRepositoryLoader } from "../loaders/TimedApiBasedRepositoryLoader";
|
||||
import { UnoptimizedInMemoryShuttleRepository } from "../repositories/shuttle/UnoptimizedInMemoryShuttleRepository";
|
||||
import { RedisNotificationRepository } from "../repositories/notifications/RedisNotificationRepository";
|
||||
import { NotificationRepository } from "../repositories/notifications/NotificationRepository";
|
||||
import { ShuttleGetterSetterRepository } from "../repositories/shuttle/ShuttleGetterSetterRepository";
|
||||
import { InMemoryNotificationRepository } from "../repositories/notifications/InMemoryNotificationRepository";
|
||||
import { AppleNotificationSender } from "../notifications/senders/AppleNotificationSender";
|
||||
import { ApiBasedShuttleRepositoryLoader } from "../loaders/shuttle/ApiBasedShuttleRepositoryLoader";
|
||||
import { ParkingGetterSetterRepository } from "../repositories/parking/ParkingGetterSetterRepository";
|
||||
import { InMemoryParkingRepository } from "../repositories/parking/InMemoryParkingRepository";
|
||||
import {
|
||||
buildParkingRepositoryLoaderIfExists,
|
||||
ParkingRepositoryLoaderBuilderArguments
|
||||
} from "../loaders/parking/buildParkingRepositoryLoaderIfExists";
|
||||
import { RedisParkingRepository } from "../repositories/parking/RedisParkingRepository";
|
||||
import { ShuttleGetterRepository } from "../repositories/shuttle/ShuttleGetterRepository";
|
||||
import { InMemoryExternalSourceETARepository } from "../repositories/shuttle/eta/InMemoryExternalSourceETARepository";
|
||||
import { ETAGetterRepository } from "../repositories/shuttle/eta/ETAGetterRepository";
|
||||
import { InMemorySelfUpdatingETARepository } from "../repositories/shuttle/eta/InMemorySelfUpdatingETARepository";
|
||||
import { BaseInMemoryETARepository } from "../repositories/shuttle/eta/BaseInMemoryETARepository";
|
||||
|
||||
export interface InterchangeSystemBuilderArguments {
|
||||
name: string;
|
||||
|
||||
/**
|
||||
* ID to identify the system internally and in the API.
|
||||
*/
|
||||
id: string;
|
||||
|
||||
/**
|
||||
* ID for fetching shuttle data from the Passio GO! system.
|
||||
*/
|
||||
passioSystemId: string;
|
||||
|
||||
/**
|
||||
* ID for the parking repository ID in the codebase.
|
||||
*/
|
||||
parkingSystemId?: string;
|
||||
|
||||
/**
|
||||
* Controls whether to self-calculate ETAs or use the external
|
||||
* shuttle provider for them.
|
||||
*/
|
||||
useSelfUpdatingEtas: boolean;
|
||||
|
||||
/**
|
||||
* The size of the threshold to detect when a shuttle has arrived
|
||||
* at a stop, in latitude/longitude degrees.
|
||||
*/
|
||||
shuttleStopArrivalDegreeDelta: number;
|
||||
}
|
||||
|
||||
export class InterchangeSystem {
|
||||
private constructor(
|
||||
public name: string,
|
||||
public id: string,
|
||||
public shuttleTimedDataLoader: TimedApiBasedRepositoryLoader,
|
||||
public shuttleRepository: ShuttleGetterSetterRepository,
|
||||
public etaRepository: ETAGetterRepository,
|
||||
public notificationScheduler: ETANotificationScheduler,
|
||||
public notificationRepository: NotificationRepository,
|
||||
public parkingTimedDataLoader: TimedApiBasedRepositoryLoader | null,
|
||||
public parkingRepository: ParkingGetterSetterRepository | null,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct an instance of the class where all composited
|
||||
* classes are correctly linked, meant for use in development and production.
|
||||
* @param args
|
||||
*/
|
||||
static async build(
|
||||
args: InterchangeSystemBuilderArguments,
|
||||
) {
|
||||
const { shuttleRepository, timedShuttleDataLoader, etaRepository } = await InterchangeSystem.buildProductionShuttleLoaderAndRepositories(args);
|
||||
timedShuttleDataLoader.start();
|
||||
|
||||
const { notificationScheduler, notificationRepository } = await InterchangeSystem.buildNotificationSchedulerAndRepository(
|
||||
etaRepository,
|
||||
shuttleRepository,
|
||||
args
|
||||
);
|
||||
notificationScheduler.startListeningForUpdates();
|
||||
|
||||
let { parkingRepository, timedParkingLoader } = await InterchangeSystem.buildRedisParkingLoaderAndRepository(args.parkingSystemId);
|
||||
timedParkingLoader?.start();
|
||||
|
||||
return new InterchangeSystem(
|
||||
args.name,
|
||||
args.id,
|
||||
timedShuttleDataLoader,
|
||||
shuttleRepository,
|
||||
etaRepository,
|
||||
notificationScheduler,
|
||||
notificationRepository,
|
||||
timedParkingLoader,
|
||||
parkingRepository,
|
||||
);
|
||||
}
|
||||
|
||||
private static async buildProductionShuttleLoaderAndRepositories(args: InterchangeSystemBuilderArguments) {
|
||||
const shuttleRepository = new UnoptimizedInMemoryShuttleRepository(
|
||||
args.shuttleStopArrivalDegreeDelta,
|
||||
);
|
||||
|
||||
let etaRepository: BaseInMemoryETARepository;
|
||||
let shuttleDataLoader: ApiBasedShuttleRepositoryLoader;
|
||||
if (args.useSelfUpdatingEtas) {
|
||||
etaRepository = new InMemorySelfUpdatingETARepository(shuttleRepository);
|
||||
(etaRepository as InMemorySelfUpdatingETARepository).startListeningForUpdates();
|
||||
shuttleDataLoader = new ApiBasedShuttleRepositoryLoader(
|
||||
args.passioSystemId,
|
||||
args.id,
|
||||
shuttleRepository,
|
||||
);
|
||||
} else {
|
||||
etaRepository = new InMemoryExternalSourceETARepository();
|
||||
shuttleDataLoader = new ApiBasedShuttleRepositoryLoader(
|
||||
args.passioSystemId,
|
||||
args.id,
|
||||
shuttleRepository,
|
||||
etaRepository as InMemoryExternalSourceETARepository,
|
||||
);
|
||||
}
|
||||
const timedShuttleDataLoader = new TimedApiBasedRepositoryLoader(
|
||||
shuttleDataLoader,
|
||||
);
|
||||
|
||||
|
||||
return { shuttleRepository, etaRepository, timedShuttleDataLoader };
|
||||
}
|
||||
|
||||
private static async buildNotificationSchedulerAndRepository(
|
||||
etaRepository: ETAGetterRepository,
|
||||
shuttleRepository: ShuttleGetterRepository,
|
||||
args: InterchangeSystemBuilderArguments
|
||||
) {
|
||||
const notificationRepository = new RedisNotificationRepository();
|
||||
await notificationRepository.connect();
|
||||
const notificationScheduler = new ETANotificationScheduler(
|
||||
etaRepository,
|
||||
shuttleRepository,
|
||||
notificationRepository,
|
||||
new AppleNotificationSender(),
|
||||
args.id
|
||||
);
|
||||
return { notificationScheduler, notificationRepository };
|
||||
}
|
||||
|
||||
private static async buildRedisParkingLoaderAndRepository(id?: string) {
|
||||
if (id === undefined) {
|
||||
return { parkingRepository: null, timedParkingLoader: null };
|
||||
}
|
||||
|
||||
let parkingRepository: RedisParkingRepository | null = new RedisParkingRepository();
|
||||
await parkingRepository.connect();
|
||||
|
||||
const loaderBuilderArguments: ParkingRepositoryLoaderBuilderArguments = {
|
||||
id,
|
||||
repository: parkingRepository,
|
||||
};
|
||||
let parkingLoader = buildParkingRepositoryLoaderIfExists(
|
||||
loaderBuilderArguments,
|
||||
);
|
||||
|
||||
let timedParkingLoader = null;
|
||||
if (parkingLoader == null) {
|
||||
parkingRepository = null;
|
||||
} else {
|
||||
timedParkingLoader = new TimedApiBasedRepositoryLoader(parkingLoader);
|
||||
}
|
||||
return { parkingRepository, timedParkingLoader };
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct an instance of the class where all composited
|
||||
* classes are correctly linked, meant for unit tests, and server/app
|
||||
* integration tests.
|
||||
* @param args
|
||||
*/
|
||||
static buildForTesting(
|
||||
args: InterchangeSystemBuilderArguments,
|
||||
) {
|
||||
const { shuttleRepository, timedShuttleLoader, etaRepository } = InterchangeSystem.buildTestingShuttleLoaderAndRepositories(args);
|
||||
// Timed shuttle loader is not started here
|
||||
|
||||
const { notificationScheduler, notificationRepository } = InterchangeSystem.buildTestingNotificationSchedulerAndRepository(
|
||||
etaRepository,
|
||||
shuttleRepository,
|
||||
args
|
||||
);
|
||||
notificationScheduler.startListeningForUpdates();
|
||||
|
||||
let { parkingRepository, timedParkingLoader } = this.buildTestingParkingLoaderAndRepository(args.parkingSystemId);
|
||||
// Timed parking loader is not started here
|
||||
|
||||
return new InterchangeSystem(
|
||||
args.name,
|
||||
args.id,
|
||||
timedShuttleLoader,
|
||||
shuttleRepository,
|
||||
etaRepository,
|
||||
notificationScheduler,
|
||||
notificationRepository,
|
||||
timedParkingLoader,
|
||||
parkingRepository,
|
||||
);
|
||||
}
|
||||
|
||||
private static buildTestingNotificationSchedulerAndRepository(
|
||||
etaRepository: ETAGetterRepository,
|
||||
shuttleRepository: UnoptimizedInMemoryShuttleRepository,
|
||||
args: InterchangeSystemBuilderArguments
|
||||
) {
|
||||
const notificationRepository = new InMemoryNotificationRepository();
|
||||
const notificationScheduler = new ETANotificationScheduler(
|
||||
etaRepository,
|
||||
shuttleRepository,
|
||||
notificationRepository,
|
||||
new AppleNotificationSender(false),
|
||||
args.id
|
||||
);
|
||||
return { notificationScheduler, notificationRepository };
|
||||
}
|
||||
|
||||
private static buildTestingParkingLoaderAndRepository(id?: string) {
|
||||
if (id === undefined) {
|
||||
return { parkingRepository: null, timedParkingLoader: null };
|
||||
}
|
||||
|
||||
let parkingRepository: ParkingGetterSetterRepository | null = new InMemoryParkingRepository();
|
||||
const loaderBuilderArguments: ParkingRepositoryLoaderBuilderArguments = {
|
||||
id,
|
||||
repository: parkingRepository,
|
||||
};
|
||||
let parkingLoader = buildParkingRepositoryLoaderIfExists(
|
||||
loaderBuilderArguments,
|
||||
);
|
||||
|
||||
let timedParkingLoader = null;
|
||||
if (parkingLoader == null) {
|
||||
parkingRepository = null;
|
||||
} else {
|
||||
timedParkingLoader = new TimedApiBasedRepositoryLoader(parkingLoader);
|
||||
}
|
||||
return { parkingRepository, timedParkingLoader };
|
||||
}
|
||||
|
||||
private static buildTestingShuttleLoaderAndRepositories(args: InterchangeSystemBuilderArguments) {
|
||||
const shuttleRepository = new UnoptimizedInMemoryShuttleRepository(
|
||||
args.shuttleStopArrivalDegreeDelta,
|
||||
);
|
||||
|
||||
let etaRepository: BaseInMemoryETARepository;
|
||||
let shuttleDataLoader: ApiBasedShuttleRepositoryLoader;
|
||||
if (args.useSelfUpdatingEtas) {
|
||||
etaRepository = new InMemorySelfUpdatingETARepository(shuttleRepository);
|
||||
(etaRepository as InMemorySelfUpdatingETARepository).startListeningForUpdates();
|
||||
shuttleDataLoader = new ApiBasedShuttleRepositoryLoader(
|
||||
args.passioSystemId,
|
||||
args.id,
|
||||
shuttleRepository,
|
||||
);
|
||||
} else {
|
||||
etaRepository = new InMemoryExternalSourceETARepository();
|
||||
shuttleDataLoader = new ApiBasedShuttleRepositoryLoader(
|
||||
args.passioSystemId,
|
||||
args.id,
|
||||
shuttleRepository,
|
||||
etaRepository as InMemoryExternalSourceETARepository,
|
||||
);
|
||||
}
|
||||
|
||||
// Note that this loader should not be started,
|
||||
// so the test data doesn't get overwritten
|
||||
const timedShuttleLoader = new TimedApiBasedRepositoryLoader(
|
||||
shuttleDataLoader
|
||||
);
|
||||
|
||||
|
||||
return { shuttleRepository, etaRepository, timedShuttleLoader };
|
||||
}
|
||||
|
||||
}
|
||||
17
src/entities/ParkingRepositoryEntities.ts
Normal file
17
src/entities/ParkingRepositoryEntities.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { ICoordinates, IEntityWithId, IEntityWithTimestamp } from "./SharedEntities";
|
||||
|
||||
export interface IParkingStructure extends IEntityWithTimestamp, IEntityWithId {
|
||||
address: string;
|
||||
capacity: number;
|
||||
spotsAvailable: number;
|
||||
coordinates: ICoordinates;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface IParkingStructureTimestampRecord {
|
||||
timestampMs: Date;
|
||||
id: string;
|
||||
spotsAvailable: number;
|
||||
}
|
||||
|
||||
// In the future, add support for viewing different levels of the structure
|
||||
13
src/entities/SharedEntities.ts
Normal file
13
src/entities/SharedEntities.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
export interface IEntityWithTimestamp {
|
||||
updatedTime: Date;
|
||||
}
|
||||
|
||||
export interface IEntityWithId {
|
||||
id: string;
|
||||
}
|
||||
|
||||
export interface ICoordinates {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
}
|
||||
|
||||
55
src/entities/ShuttleRepositoryEntities.ts
Normal file
55
src/entities/ShuttleRepositoryEntities.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { ICoordinates, IEntityWithId, IEntityWithTimestamp } from "./SharedEntities";
|
||||
|
||||
export interface IRoute extends IEntityWithId, IEntityWithTimestamp {
|
||||
name: string;
|
||||
color: string;
|
||||
polylineCoordinates: ICoordinates[];
|
||||
systemId: string;
|
||||
}
|
||||
|
||||
export interface IStop extends IEntityWithId, IEntityWithTimestamp {
|
||||
name: string;
|
||||
systemId: string;
|
||||
coordinates: ICoordinates;
|
||||
}
|
||||
|
||||
export interface IShuttle extends IEntityWithId, IEntityWithTimestamp {
|
||||
coordinates: ICoordinates;
|
||||
name: string;
|
||||
routeId: string;
|
||||
systemId: string;
|
||||
orientationInDegrees: number;
|
||||
}
|
||||
|
||||
export interface IEta extends IEntityWithTimestamp {
|
||||
secondsRemaining: number;
|
||||
shuttleId: string;
|
||||
stopId: string;
|
||||
systemId: string;
|
||||
}
|
||||
|
||||
export interface IOrderedStop extends IEntityWithTimestamp {
|
||||
nextStop?: IOrderedStop;
|
||||
previousStop?: IOrderedStop;
|
||||
routeId: string;
|
||||
stopId: string;
|
||||
position: number;
|
||||
systemId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a shuttle has arrived at a stop based on coordinate proximity.
|
||||
* Uses a threshold of 0.001 degrees (~111 meters at the equator).
|
||||
*/
|
||||
export function shuttleHasArrivedAtStop(
|
||||
shuttle: IShuttle,
|
||||
stop: IStop,
|
||||
delta = 0.001
|
||||
) {
|
||||
const isWithinLatitudeRange = shuttle.coordinates.latitude > stop.coordinates.latitude - delta
|
||||
&& shuttle.coordinates.latitude < stop.coordinates.latitude + delta;
|
||||
const isWithinLongitudeRange = shuttle.coordinates.longitude > stop.coordinates.longitude - delta
|
||||
&& shuttle.coordinates.longitude < stop.coordinates.longitude + delta
|
||||
return isWithinLatitudeRange && isWithinLongitudeRange;
|
||||
}
|
||||
|
||||
65
src/entities/__tests__/ShuttleRepositoryEntities.test.ts
Normal file
65
src/entities/__tests__/ShuttleRepositoryEntities.test.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it } from "@jest/globals";
|
||||
import { shuttleHasArrivedAtStop, IShuttle, IStop } from "../ShuttleRepositoryEntities";
|
||||
|
||||
describe("shuttleHasArrivedAtStop", () => {
|
||||
const baseStop: IStop = {
|
||||
id: "stop1",
|
||||
name: "Test Stop",
|
||||
systemId: "263",
|
||||
coordinates: {
|
||||
latitude: 33.7963,
|
||||
longitude: -117.8540,
|
||||
},
|
||||
updatedTime: new Date(),
|
||||
};
|
||||
|
||||
const createShuttle = (latitude: number, longitude: number): IShuttle => ({
|
||||
id: "shuttle1",
|
||||
name: "Test Shuttle",
|
||||
routeId: "route1",
|
||||
systemId: "263",
|
||||
coordinates: { latitude, longitude },
|
||||
orientationInDegrees: 0,
|
||||
updatedTime: new Date(),
|
||||
});
|
||||
|
||||
it("returns false when shuttle is above latitude range", () => {
|
||||
const shuttle = createShuttle(
|
||||
baseStop.coordinates.latitude + 0.0011,
|
||||
baseStop.coordinates.longitude
|
||||
);
|
||||
expect(shuttleHasArrivedAtStop(shuttle, baseStop)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false when shuttle is below latitude range", () => {
|
||||
const shuttle = createShuttle(
|
||||
baseStop.coordinates.latitude - 0.0011,
|
||||
baseStop.coordinates.longitude
|
||||
);
|
||||
expect(shuttleHasArrivedAtStop(shuttle, baseStop)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false when shuttle is to left of longitude range", () => {
|
||||
const shuttle = createShuttle(
|
||||
baseStop.coordinates.latitude,
|
||||
baseStop.coordinates.longitude - 0.0011
|
||||
);
|
||||
expect(shuttleHasArrivedAtStop(shuttle, baseStop)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false when shuttle is to right of longitude range", () => {
|
||||
const shuttle = createShuttle(
|
||||
baseStop.coordinates.latitude,
|
||||
baseStop.coordinates.longitude + 0.0011
|
||||
);
|
||||
expect(shuttleHasArrivedAtStop(shuttle, baseStop)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns true when shuttle is in the range", () => {
|
||||
const shuttle = createShuttle(
|
||||
baseStop.coordinates.latitude + 0.0005,
|
||||
baseStop.coordinates.longitude - 0.0005
|
||||
);
|
||||
expect(shuttleHasArrivedAtStop(shuttle, baseStop)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,51 +0,0 @@
|
||||
export interface IEntityWithOptionalTimestamp {
|
||||
millisecondsSinceEpoch?: number;
|
||||
}
|
||||
|
||||
export interface IEntityWithId {
|
||||
id: string;
|
||||
}
|
||||
|
||||
export interface ISystem extends IEntityWithId, IEntityWithOptionalTimestamp {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface ICoordinates {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
}
|
||||
|
||||
export interface IRoute extends IEntityWithId, IEntityWithOptionalTimestamp {
|
||||
name: string;
|
||||
color: string;
|
||||
polylineCoordinates: ICoordinates[];
|
||||
systemId: string;
|
||||
}
|
||||
|
||||
export interface IStop extends IEntityWithId, IEntityWithOptionalTimestamp {
|
||||
name: string;
|
||||
systemId: string;
|
||||
coordinates: ICoordinates;
|
||||
}
|
||||
|
||||
export interface IShuttle extends IEntityWithId, IEntityWithOptionalTimestamp {
|
||||
coordinates: ICoordinates;
|
||||
name: string;
|
||||
routeId: string;
|
||||
systemId: string;
|
||||
}
|
||||
|
||||
export interface IEta extends IEntityWithOptionalTimestamp {
|
||||
secondsRemaining: number;
|
||||
shuttleId: string;
|
||||
stopId: string;
|
||||
}
|
||||
|
||||
export interface IOrderedStop extends IEntityWithOptionalTimestamp {
|
||||
nextStop?: IOrderedStop;
|
||||
previousStop?: IOrderedStop;
|
||||
routeId: string;
|
||||
stopId: string;
|
||||
position: number;
|
||||
}
|
||||
|
||||
26
src/environment.ts
Normal file
26
src/environment.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
export const PARKING_LOGGING_INTERVAL_MS = process.env.PARKING_LOGGING_INTERVAL_MS
|
||||
? parseInt(process.env.PARKING_LOGGING_INTERVAL_MS)
|
||||
: 600000; // Every 10 minutes
|
||||
|
||||
export const PARKING_HISTORICAL_AVERAGE_MINIMUM_INTERVAL = process.env.PARKING_HISTORICAL_AVERAGE_MINIMUM_INTERVAL
|
||||
? parseInt(process.env.PARKING_HISTORICAL_AVERAGE_MINIMUM_INTERVAL)
|
||||
: 60000 * 60 * 2;
|
||||
|
||||
export const PARKING_HISTORICAL_AVERAGE_MAXIMUM_TIMESPAN = process.env.PARKING_HISTORICAL_AVERAGE_MAXIMUM_TIMESPAN
|
||||
? parseInt(process.env.PARKING_HISTORICAL_AVERAGE_MAXIMUM_TIMESPAN)
|
||||
: 60000 * 60 * 24;
|
||||
|
||||
export const RATE_LIMITS_DISABLED = process.env.RATE_LIMITS_DISABLED === "1";
|
||||
export const RATE_LIMIT_WINDOW_MS = process.env.RATE_LIMIT_WINDOW_MS
|
||||
? parseInt(process.env.RATE_LIMIT_WINDOW_MS)
|
||||
: 10000;
|
||||
export const RATE_LIMIT_DELAY_AFTER_REQUESTS = process.env.RATE_LIMIT_DELAY_AFTER_REQUESTS
|
||||
? parseInt(process.env.RATE_LIMIT_DELAY_AFTER_REQUESTS)
|
||||
: 10000;
|
||||
export const RATE_LIMIT_DELAY_MULTIPLIER_MS = process.env.RATE_LIMIT_DELAY_MULTIPLIER_MS
|
||||
? parseInt(process.env.RATE_LIMIT_DELAY_MULTIPLIER_MS)
|
||||
: 1000;
|
||||
|
||||
export const REDIS_RECONNECT_INTERVAL = 30000;
|
||||
|
||||
export const SHUTTLE_TO_ROUTE_COORDINATE_MAXIMUM_DISTANCE_MILES = 5;
|
||||
15
src/helpers/createRedisClientForRepository.ts
Normal file
15
src/helpers/createRedisClientForRepository.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { createClient, RedisClientType } from "redis";
|
||||
import { REDIS_RECONNECT_INTERVAL } from "../environment";
|
||||
|
||||
export default function createRedisClientForRepository() {
|
||||
const client = createClient({
|
||||
url: process.env.REDIS_URL,
|
||||
socket: {
|
||||
tls: process.env.REDIS_USE_TLS === "1",
|
||||
rejectUnauthorized: false,
|
||||
reconnectStrategy: REDIS_RECONNECT_INTERVAL,
|
||||
} as object,
|
||||
});
|
||||
return client as RedisClientType;
|
||||
}
|
||||
|
||||
86
src/index.ts
86
src/index.ts
@@ -1,41 +1,91 @@
|
||||
import { readFileSync } from "fs";
|
||||
import { ApolloServer } from "@apollo/server";
|
||||
import { startStandaloneServer } from "@apollo/server/standalone";
|
||||
import { MergedResolvers } from "./MergedResolvers";
|
||||
import { ServerContext } from "./ServerContext";
|
||||
import { UnoptimizedInMemoryRepository } from "./repositories/UnoptimizedInMemoryRepository";
|
||||
import { TimedApiBasedRepositoryLoader } from "./loaders/TimedApiBasedRepositoryLoader";
|
||||
import { InterchangeSystem, InterchangeSystemBuilderArguments } from "./entities/InterchangeSystem";
|
||||
import { ChapmanApiBasedParkingRepositoryLoader } from "./loaders/parking/ChapmanApiBasedParkingRepositoryLoader";
|
||||
import express from "express";
|
||||
import { expressMiddleware } from "@as-integrations/express5";
|
||||
import {
|
||||
RATE_LIMIT_DELAY_AFTER_REQUESTS,
|
||||
RATE_LIMIT_DELAY_MULTIPLIER_MS,
|
||||
RATE_LIMIT_WINDOW_MS,
|
||||
RATE_LIMITS_DISABLED
|
||||
} from "./environment";
|
||||
import slowDown from "express-slow-down";
|
||||
|
||||
const typeDefs = readFileSync("./schema.graphqls", "utf8");
|
||||
|
||||
// In the future this can be stored as a separate file
|
||||
const supportedSystems: InterchangeSystemBuilderArguments[] = [
|
||||
{
|
||||
id: "1",
|
||||
passioSystemId: "263",
|
||||
parkingSystemId: ChapmanApiBasedParkingRepositoryLoader.id,
|
||||
name: "Chapman University",
|
||||
useSelfUpdatingEtas: true,
|
||||
shuttleStopArrivalDegreeDelta: 0.001,
|
||||
}
|
||||
]
|
||||
|
||||
async function main() {
|
||||
const server = new ApolloServer<ServerContext>({
|
||||
typeDefs,
|
||||
resolvers: MergedResolvers,
|
||||
introspection: process.env.NODE_ENV !== "production",
|
||||
});
|
||||
await server.start();
|
||||
|
||||
const repository = new UnoptimizedInMemoryRepository();
|
||||
// await loadTestData(repository);
|
||||
let systems: InterchangeSystem[];
|
||||
|
||||
const repositoryDataUpdater = new TimedApiBasedRepositoryLoader(
|
||||
repository
|
||||
);
|
||||
await repositoryDataUpdater.start();
|
||||
|
||||
const { url } = await startStandaloneServer(server, {
|
||||
listen: {
|
||||
port: process.env.PORT ? parseInt(process.env.PORT) : 4000,
|
||||
systems = await Promise.all(supportedSystems.map(
|
||||
async (systemArguments) => {
|
||||
return await InterchangeSystem.build(systemArguments);
|
||||
},
|
||||
context: async ({ req, res }) => {
|
||||
));
|
||||
|
||||
const app = express();
|
||||
const options = {
|
||||
context: async () => {
|
||||
return {
|
||||
repository,
|
||||
systems,
|
||||
findSystemById: (id: string) => {
|
||||
const system = systems.find((system) => system.id === id);
|
||||
if (!system) {
|
||||
return null;
|
||||
}
|
||||
return system;
|
||||
},
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
if (RATE_LIMITS_DISABLED) {
|
||||
app.use(
|
||||
"/",
|
||||
express.json(),
|
||||
expressMiddleware(server, options)
|
||||
);
|
||||
} else {
|
||||
const limiter = slowDown({
|
||||
windowMs: RATE_LIMIT_WINDOW_MS,
|
||||
delayAfter: RATE_LIMIT_DELAY_AFTER_REQUESTS,
|
||||
delayMs: (hits) => {
|
||||
return hits * RATE_LIMIT_DELAY_MULTIPLIER_MS;
|
||||
}
|
||||
});
|
||||
app.use(
|
||||
"/",
|
||||
express.json(),
|
||||
limiter,
|
||||
expressMiddleware(server, options),
|
||||
);
|
||||
}
|
||||
|
||||
const port = process.env.PORT ? parseInt(process.env.PORT) : 4000;
|
||||
app.listen(port, () => {
|
||||
console.log(`Server ready at port ${port}`);
|
||||
});
|
||||
|
||||
|
||||
console.log(`Server ready at: ${url}`);
|
||||
}
|
||||
|
||||
main();
|
||||
|
||||
@@ -1,385 +0,0 @@
|
||||
import { GetterSetterRepository } from "../repositories/GetterSetterRepository";
|
||||
import { IEntityWithId, IEta, IRoute, IShuttle, IStop, ISystem } from "../entities/entities";
|
||||
|
||||
export class ApiResponseError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "ApiResponseError";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Class which can load data into a repository from the
|
||||
* Passio Go API. Supports automatic pruning of all data types
|
||||
* which inherit from `IEntityWithId`.
|
||||
*/
|
||||
export class ApiBasedRepositoryLoader {
|
||||
supportedSystemIds = ["263"];
|
||||
baseUrl = "https://passiogo.com/mapGetData.php";
|
||||
|
||||
constructor(
|
||||
public repository: GetterSetterRepository,
|
||||
) {
|
||||
}
|
||||
|
||||
private async constructExistingEntityIdSet<T extends IEntityWithId>(entitySearchCallback: () => Promise<T[]>) {
|
||||
const existingEntities = await entitySearchCallback();
|
||||
const ids = new Set<string>();
|
||||
existingEntities.forEach((entity) => {
|
||||
ids.add(entity.id);
|
||||
});
|
||||
return ids;
|
||||
}
|
||||
|
||||
public async fetchAndUpdateSystemData() {
|
||||
const params = {
|
||||
getSystems: "2",
|
||||
};
|
||||
const query = new URLSearchParams(params).toString();
|
||||
|
||||
const systemIds = await this.constructExistingEntityIdSet(async () => {
|
||||
return await this.repository.getSystems();
|
||||
})
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}?${query}`);
|
||||
const json = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error with status ${response.status}`)
|
||||
}
|
||||
|
||||
if (typeof json.all === "object") {
|
||||
// filter down to supported systems
|
||||
const filteredSystems = json.all.filter((jsonSystem: any) => this.supportedSystemIds.includes(jsonSystem.id));
|
||||
await Promise.all(filteredSystems.map(async (system: any) => {
|
||||
const constructedSystem: ISystem = {
|
||||
id: system.id,
|
||||
name: system.fullname,
|
||||
};
|
||||
|
||||
await this.repository.addOrUpdateSystem(constructedSystem);
|
||||
systemIds.delete(constructedSystem.id);
|
||||
}));
|
||||
} else {
|
||||
throw new Error("Received JSON object does not contain `all` field")
|
||||
}
|
||||
|
||||
// Prune systems
|
||||
await Promise.all(Array.from(systemIds).map(async (systemId) => {
|
||||
await this.repository.removeSystemIfExists(systemId);
|
||||
}));
|
||||
} catch(e: any) {
|
||||
throw new ApiResponseError(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
public async fetchAndUpdateRouteDataForExistingSystemsInRepository() {
|
||||
const systems = await this.repository.getSystems();
|
||||
await Promise.all(systems.map(async (system) => {
|
||||
await this.fetchAndUpdateRouteDataForSystemId(system.id);
|
||||
}));
|
||||
}
|
||||
|
||||
public async fetchAndUpdateRouteDataForSystemId(systemId: string) {
|
||||
const routeIdsToPrune = await this.constructExistingEntityIdSet(async () => {
|
||||
return await this.repository.getRoutesBySystemId(systemId);
|
||||
});
|
||||
|
||||
const params = {
|
||||
getRoutes: "2",
|
||||
};
|
||||
|
||||
const formDataJsonObject = {
|
||||
"systemSelected0": systemId,
|
||||
"amount": "1",
|
||||
}
|
||||
const formData = new FormData();
|
||||
formData.set("json", JSON.stringify(formDataJsonObject));
|
||||
|
||||
const query = new URLSearchParams(params).toString();
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}?${query}`, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
const json = await response.json();
|
||||
|
||||
if (typeof json.all === "object") {
|
||||
await Promise.all(json.all.map(async (jsonRoute: any) => {
|
||||
const constructedRoute: IRoute = {
|
||||
name: jsonRoute.name,
|
||||
color: jsonRoute.color,
|
||||
id: jsonRoute.myid,
|
||||
polylineCoordinates: [],
|
||||
systemId: systemId,
|
||||
};
|
||||
|
||||
await this.repository.addOrUpdateRoute(constructedRoute);
|
||||
|
||||
routeIdsToPrune.delete(constructedRoute.id);
|
||||
}))
|
||||
}
|
||||
|
||||
await Promise.all(Array.from(routeIdsToPrune).map(async (routeId) => {
|
||||
await this.repository.removeRouteIfExists(routeId);
|
||||
}));
|
||||
} catch(e: any) {
|
||||
throw new ApiResponseError(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
public async fetchAndUpdateStopAndPolylineDataForRoutesInExistingSystemsInRepository() {
|
||||
const systems = await this.repository.getSystems();
|
||||
await Promise.all(systems.map(async (system: ISystem) => {
|
||||
await this.fetchAndUpdateStopAndPolylineDataForRoutesWithSystemId(system.id);
|
||||
}));
|
||||
}
|
||||
|
||||
public async fetchAndUpdateStopAndPolylineDataForRoutesWithSystemId(systemId: string) {
|
||||
// Fetch from the API
|
||||
// Pass JSON output into two different methods to update repository
|
||||
const stopIdsToPrune = await this.constructExistingEntityIdSet(async () => {
|
||||
return await this.repository.getStopsBySystemId(systemId);
|
||||
});
|
||||
|
||||
const params = {
|
||||
getStops: "2",
|
||||
};
|
||||
|
||||
const formDataJsonObject = {
|
||||
"s0": systemId,
|
||||
"sA": 1
|
||||
};
|
||||
const formData = new FormData();
|
||||
formData.set("json", JSON.stringify(formDataJsonObject));
|
||||
|
||||
const query = new URLSearchParams(params).toString();
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}?${query}`, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
const json = await response.json();
|
||||
|
||||
await this.updateStopDataForSystemAndApiResponse(systemId, json, stopIdsToPrune);
|
||||
await this.updateOrderedStopDataForExistingStops(json);
|
||||
await this.updatePolylineDataForExistingRoutesAndApiResponse(json);
|
||||
|
||||
await Promise.all(Array.from(stopIdsToPrune).map(async (stopId) => {
|
||||
await this.repository.removeStopIfExists(stopId);
|
||||
}));
|
||||
} catch(e: any) {
|
||||
throw new ApiResponseError(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
public async fetchAndUpdateShuttleDataForExistingSystemsInRepository() {
|
||||
const systems = await this.repository.getSystems();
|
||||
await Promise.all(systems.map(async (system: ISystem) => {
|
||||
const systemId = system.id;
|
||||
await this.fetchAndUpdateShuttleDataForSystemId(systemId);
|
||||
}));
|
||||
}
|
||||
|
||||
public async fetchAndUpdateShuttleDataForSystemId(systemId: string) {
|
||||
const shuttleIdsToPrune = await this.constructExistingEntityIdSet(async () => {
|
||||
return await this.repository.getShuttlesBySystemId(systemId);
|
||||
});
|
||||
|
||||
const params = {
|
||||
getBuses: "2"
|
||||
};
|
||||
|
||||
const formDataJsonObject = {
|
||||
"s0": systemId,
|
||||
"sA": "1"
|
||||
};
|
||||
|
||||
const formData = new FormData();
|
||||
formData.set("json", JSON.stringify(formDataJsonObject));
|
||||
|
||||
const query = new URLSearchParams(params).toString();
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}?${query}`, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
const json = await response.json();
|
||||
|
||||
if (json.buses && json.buses["-1"] === undefined) {
|
||||
const jsonBuses = Object.values(json.buses).map((busesArr: any) => {
|
||||
return busesArr[0];
|
||||
});
|
||||
|
||||
await Promise.all(jsonBuses.map(async (jsonBus: any) => {
|
||||
const constructedShuttle: IShuttle = {
|
||||
name: jsonBus.bus,
|
||||
coordinates: {
|
||||
latitude: parseFloat(jsonBus.latitude),
|
||||
longitude: parseFloat(jsonBus.longitude),
|
||||
},
|
||||
routeId: jsonBus.routeId,
|
||||
systemId: systemId,
|
||||
id: `${jsonBus.busId}`
|
||||
}
|
||||
|
||||
await this.repository.addOrUpdateShuttle(constructedShuttle);
|
||||
|
||||
shuttleIdsToPrune.delete(constructedShuttle.id);
|
||||
}));
|
||||
}
|
||||
|
||||
await Promise.all(Array.from(shuttleIdsToPrune).map(async (shuttleId) => {
|
||||
await this.repository.removeShuttleIfExists(shuttleId);
|
||||
}));
|
||||
} catch(e: any) {
|
||||
throw new ApiResponseError(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
public async fetchAndUpdateEtaDataForExistingStopsForSystemsInRepository() {
|
||||
const systems = await this.repository.getSystems()
|
||||
await Promise.all(systems.map(async (system: ISystem) => {
|
||||
const systemId = system.id;
|
||||
await this.fetchAndUpdateEtaDataForExistingStopsForSystemId(systemId);
|
||||
}))
|
||||
}
|
||||
|
||||
public async fetchAndUpdateEtaDataForExistingStopsForSystemId(systemId: string) {
|
||||
const stops = await this.repository.getStopsBySystemId(systemId);
|
||||
await Promise.all(stops.map(async (stop) => {
|
||||
let stopId = stop.id;
|
||||
await this.fetchAndUpdateEtaDataForStopId(stopId);
|
||||
}));
|
||||
}
|
||||
|
||||
public async fetchAndUpdateEtaDataForStopId(stopId: string) {
|
||||
const params = {
|
||||
eta: "3",
|
||||
stopIds: stopId,
|
||||
};
|
||||
|
||||
const query = new URLSearchParams(params).toString();
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.baseUrl}?${query}`, {
|
||||
method: "GET",
|
||||
});
|
||||
const json = await response.json();
|
||||
|
||||
if (json.ETAs && json.ETAs[stopId]) {
|
||||
// Continue with the parsing
|
||||
json.ETAs[stopId].forEach((jsonEta: any) => {
|
||||
// Update cache
|
||||
const shuttleId: string = jsonEta.busId;
|
||||
|
||||
const eta: IEta = {
|
||||
secondsRemaining: jsonEta.secondsSpent,
|
||||
shuttleId: `${shuttleId}`,
|
||||
stopId: stopId,
|
||||
millisecondsSinceEpoch: Date.now(),
|
||||
};
|
||||
|
||||
this.repository.addOrUpdateEta(eta);
|
||||
});
|
||||
}
|
||||
} catch(e: any) {
|
||||
throw new ApiResponseError(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
protected async updateStopDataForSystemAndApiResponse(
|
||||
systemId: string,
|
||||
json: any,
|
||||
setOfIdsToPrune: Set<string> = new Set(),
|
||||
) {
|
||||
if (json.stops) {
|
||||
const jsonStops = Object.values(json.stops);
|
||||
|
||||
await Promise.all(jsonStops.map(async (stop: any) => {
|
||||
const constructedStop: IStop = {
|
||||
name: stop.name,
|
||||
id: stop.id,
|
||||
systemId,
|
||||
coordinates: {
|
||||
latitude: parseFloat(stop.latitude),
|
||||
longitude: parseFloat(stop.longitude),
|
||||
},
|
||||
};
|
||||
|
||||
await this.repository.addOrUpdateStop(constructedStop);
|
||||
|
||||
setOfIdsToPrune.delete(constructedStop.id);
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
protected async updateOrderedStopDataForExistingStops(json: any) {
|
||||
if (json.routes) {
|
||||
await Promise.all(Object.keys(json.routes).map(async (routeId) => {
|
||||
const jsonOrderedStopData: any[][] = json.routes[routeId].slice(2);
|
||||
|
||||
// The API may return the same stop twice to indicate that
|
||||
// the route runs in a loop
|
||||
// If the API does not do this, assume the route is one-way
|
||||
// To account for this, check if ordered stop already exists in repo
|
||||
// If it does, write to that stop instead
|
||||
|
||||
for (let index = 0; index < jsonOrderedStopData.length; index++) {
|
||||
const orderedStopDataArray = jsonOrderedStopData[index];
|
||||
|
||||
const stopId = orderedStopDataArray[1];
|
||||
let constructedOrderedStop = await this.repository.getOrderedStopByRouteAndStopId(routeId, stopId)
|
||||
if (constructedOrderedStop === null) {
|
||||
constructedOrderedStop = {
|
||||
routeId,
|
||||
stopId,
|
||||
position: index + 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (index >= 1) {
|
||||
constructedOrderedStop.previousStop = {
|
||||
routeId,
|
||||
stopId: jsonOrderedStopData[index - 1][1],
|
||||
position: index,
|
||||
};
|
||||
}
|
||||
if (index < jsonOrderedStopData.length - 1) {
|
||||
constructedOrderedStop.nextStop = {
|
||||
routeId,
|
||||
stopId: jsonOrderedStopData[index + 1][1],
|
||||
position: index + 2,
|
||||
};
|
||||
}
|
||||
|
||||
await this.repository.addOrUpdateOrderedStop(constructedOrderedStop);
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
protected async updatePolylineDataForExistingRoutesAndApiResponse(json: any) {
|
||||
if (json.routePoints) {
|
||||
await Promise.all(Object.keys(json.routePoints).map(async (routeId) => {
|
||||
const routePoints = json.routePoints[routeId][0];
|
||||
|
||||
const existingRoute = await this.repository.getRouteById(routeId);
|
||||
if (!existingRoute) return;
|
||||
|
||||
existingRoute.polylineCoordinates = routePoints.map((point: any) => {
|
||||
return {
|
||||
latitude: parseFloat(point.lat),
|
||||
longitude: parseFloat(point.lng),
|
||||
};
|
||||
});
|
||||
|
||||
await this.repository.addOrUpdateRoute(existingRoute);
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
6
src/loaders/ApiResponseError.ts
Normal file
6
src/loaders/ApiResponseError.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export class ApiResponseError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "ApiResponseError";
|
||||
}
|
||||
}
|
||||
3
src/loaders/RepositoryLoader.ts
Normal file
3
src/loaders/RepositoryLoader.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export interface RepositoryLoader {
|
||||
updateAll(): Promise<void>;
|
||||
}
|
||||
@@ -1,31 +1,17 @@
|
||||
import { GetterSetterRepository } from "../repositories/GetterSetterRepository";
|
||||
import { IEta, IRoute, IShuttle, IStop, ISystem } from "../entities/entities";
|
||||
import { ApiBasedRepositoryLoader } from "./ApiBasedRepositoryLoader";
|
||||
import { RepositoryLoader } from "./RepositoryLoader";
|
||||
|
||||
// Ideas to break this into smaller pieces in the future:
|
||||
// Have one repository data loader running for each supported system
|
||||
// Each data loader independently updates data based on frequency of usage
|
||||
// To break down timed loading in the future:
|
||||
// Add flags to the repository indicating which data users are subscribed to
|
||||
// In the loader's `fetchAll` method, check flags and update only needed data
|
||||
|
||||
// Notes on this: we only need to reload ETA data frequently
|
||||
// Other data can be reloaded periodically
|
||||
// Detailed list:
|
||||
// - ETA: reload frequently or switch to write-through approach
|
||||
// - Shuttles: reload every minute
|
||||
// - Routes: reload every few minutes
|
||||
// - Stops: reload every few minutes
|
||||
// - OrderedStops: reload every few minutes
|
||||
// - Systems: reload once a day
|
||||
|
||||
export class TimedApiBasedRepositoryLoader extends ApiBasedRepositoryLoader {
|
||||
export class TimedApiBasedRepositoryLoader {
|
||||
private shouldBeRunning: boolean = false;
|
||||
private timer: any;
|
||||
|
||||
readonly timeout = 10000;
|
||||
|
||||
constructor(
|
||||
repository: GetterSetterRepository,
|
||||
public loader: RepositoryLoader,
|
||||
public readonly timeoutMs: number = 10000,
|
||||
) {
|
||||
super(repository);
|
||||
this.startFetchDataAndUpdate = this.startFetchDataAndUpdate.bind(this);
|
||||
}
|
||||
|
||||
@@ -47,19 +33,11 @@ export class TimedApiBasedRepositoryLoader extends ApiBasedRepositoryLoader {
|
||||
if (!this.shouldBeRunning) return;
|
||||
|
||||
try {
|
||||
await this.fetchAndUpdateSystemData();
|
||||
await this.fetchAndUpdateRouteDataForExistingSystemsInRepository();
|
||||
await this.fetchAndUpdateStopAndPolylineDataForRoutesInExistingSystemsInRepository();
|
||||
await this.fetchAndUpdateShuttleDataForExistingSystemsInRepository();
|
||||
|
||||
// Because ETA method doesn't support pruning yet,
|
||||
// add a call to the clear method here
|
||||
await this.repository.clearEtaData();
|
||||
await this.fetchAndUpdateEtaDataForExistingStopsForSystemsInRepository();
|
||||
await this.loader.updateAll();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
|
||||
this.timer = setTimeout(this.startFetchDataAndUpdate, this.timeout);
|
||||
this.timer = setTimeout(this.startFetchDataAndUpdate, this.timeoutMs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
import { TimedApiBasedRepositoryLoader } from "../TimedApiBasedRepositoryLoader";
|
||||
import { resetGlobalFetchMockJson } from "../../../testHelpers/fetchMockHelpers";
|
||||
import { UnoptimizedInMemoryShuttleRepository } from "../../repositories/shuttle/UnoptimizedInMemoryShuttleRepository";
|
||||
import { ApiBasedShuttleRepositoryLoader } from "../shuttle/ApiBasedShuttleRepositoryLoader";
|
||||
|
||||
describe("TimedApiBasedRepositoryLoader", () => {
|
||||
let timedLoader: TimedApiBasedRepositoryLoader;
|
||||
let spies: any;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers();
|
||||
jest.spyOn(global, "setTimeout");
|
||||
resetGlobalFetchMockJson();
|
||||
|
||||
const mockLoader = new ApiBasedShuttleRepositoryLoader(
|
||||
"1",
|
||||
"1",
|
||||
new UnoptimizedInMemoryShuttleRepository(),
|
||||
);
|
||||
timedLoader = new TimedApiBasedRepositoryLoader(
|
||||
mockLoader,
|
||||
);
|
||||
|
||||
spies = {
|
||||
updateAll: jest.spyOn(mockLoader, 'updateAll'),
|
||||
};
|
||||
|
||||
Object.values(spies).forEach((spy: any) => {
|
||||
spy.mockResolvedValue(undefined);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
jest.clearAllTimers();
|
||||
})
|
||||
|
||||
describe("start", () => {
|
||||
it("should update internal state, call data fetching methods, and start a timer", async () => {
|
||||
await timedLoader.start();
|
||||
expect(timedLoader["shouldBeRunning"]).toBe(true);
|
||||
|
||||
Object.values(spies).forEach((spy: any) => {
|
||||
expect(spy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
expect(setTimeout).toHaveBeenCalledWith(expect.any(Function), timedLoader.timeoutMs);
|
||||
expect(timedLoader.timeoutMs).not.toBeUndefined();
|
||||
});
|
||||
|
||||
it("does nothing if timer is already running", async () => {
|
||||
await timedLoader.start();
|
||||
await timedLoader.start();
|
||||
|
||||
Object.values(spies).forEach((spy: any) => {
|
||||
expect(spy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("stop", () => {
|
||||
it("should update internal state", async () => {
|
||||
timedLoader.stop();
|
||||
expect(timedLoader['shouldBeRunning']).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,131 +0,0 @@
|
||||
// Mock data
|
||||
import { IEta, IOrderedStop, IRoute, IShuttle, IStop, ISystem } from "../entities/entities";
|
||||
import { GetterSetterRepository } from "../repositories/GetterSetterRepository";
|
||||
|
||||
// TODO: turn this into a class for testing reusability
|
||||
|
||||
const systems: ISystem[] = [
|
||||
{
|
||||
id: "1",
|
||||
name: "Chapman University",
|
||||
},
|
||||
];
|
||||
|
||||
const routes: IRoute[] = [
|
||||
{
|
||||
name: "Red Route",
|
||||
id: "1",
|
||||
systemId: systems[0].id,
|
||||
polylineCoordinates: [],
|
||||
color: "#db2316",
|
||||
},
|
||||
{
|
||||
name: "Teal Route",
|
||||
id: "2",
|
||||
systemId: systems[0].id,
|
||||
polylineCoordinates: [],
|
||||
color: "#21bdd1",
|
||||
},
|
||||
];
|
||||
|
||||
const stops: IStop[] = [
|
||||
{
|
||||
id: "1",
|
||||
name: "Chapman Court",
|
||||
coordinates: {
|
||||
latitude: 33.796001,
|
||||
longitude: -117.8892805,
|
||||
},
|
||||
systemId: systems[0].id,
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
name: "Chapman Grand",
|
||||
coordinates: {
|
||||
latitude: 33.804433,
|
||||
longitude: -117.895966,
|
||||
},
|
||||
systemId: systems[0].id,
|
||||
}
|
||||
];
|
||||
|
||||
const orderedStopsForRedRoute: IOrderedStop[] = [
|
||||
{
|
||||
routeId: routes[0].id,
|
||||
stopId: stops[0].id,
|
||||
position: 1,
|
||||
},
|
||||
{
|
||||
routeId: routes[0].id,
|
||||
stopId: stops[1].id,
|
||||
position: 2,
|
||||
},
|
||||
];
|
||||
|
||||
const orderedStopsForTealRoute: IOrderedStop[] = [
|
||||
{
|
||||
routeId: routes[1].id,
|
||||
stopId: stops[1].id,
|
||||
position: 1,
|
||||
},
|
||||
{
|
||||
routeId: routes[1].id,
|
||||
stopId: stops[0].id,
|
||||
position: 2,
|
||||
},
|
||||
]
|
||||
|
||||
orderedStopsForRedRoute[0].nextStop = orderedStopsForRedRoute[1];
|
||||
orderedStopsForRedRoute[1].previousStop = orderedStopsForRedRoute[0];
|
||||
orderedStopsForTealRoute[0].nextStop = orderedStopsForTealRoute[1];
|
||||
orderedStopsForTealRoute[1].previousStop = orderedStopsForTealRoute[0];
|
||||
|
||||
const shuttles: IShuttle[] = [
|
||||
{
|
||||
name: "Red Shuttle 17",
|
||||
id: "1",
|
||||
coordinates: {
|
||||
latitude: 33.796001,
|
||||
longitude: -117.8892805,
|
||||
},
|
||||
routeId: routes[0].id,
|
||||
systemId: systems[0].id,
|
||||
}
|
||||
];
|
||||
|
||||
const etas: IEta[] = [
|
||||
{
|
||||
stopId: stops[0].id,
|
||||
shuttleId: shuttles[0].id,
|
||||
secondsRemaining: 12.023,
|
||||
},
|
||||
{
|
||||
stopId: stops[1].id,
|
||||
shuttleId: shuttles[0].id,
|
||||
secondsRemaining: 600.123,
|
||||
}
|
||||
];
|
||||
|
||||
export async function loadTestData(repository: GetterSetterRepository) {
|
||||
await Promise.all(systems.map(async (system) => {
|
||||
await repository.addOrUpdateSystem(system);
|
||||
}));
|
||||
await Promise.all(routes.map(async (route) => {
|
||||
await repository.addOrUpdateRoute(route);
|
||||
}));
|
||||
await Promise.all(shuttles.map(async (shuttle) => {
|
||||
await repository.addOrUpdateShuttle(shuttle);
|
||||
}));
|
||||
await Promise.all(stops.map(async (stop) => {
|
||||
await repository.addOrUpdateStop(stop);
|
||||
}));
|
||||
await Promise.all(orderedStopsForRedRoute.map(async (orderedStop) => {
|
||||
await repository.addOrUpdateOrderedStop(orderedStop);
|
||||
}));
|
||||
await Promise.all(orderedStopsForTealRoute.map(async (orderedStop) => {
|
||||
await repository.addOrUpdateOrderedStop(orderedStop);
|
||||
}));
|
||||
await Promise.all(etas.map(async (eta) => {
|
||||
await repository.addOrUpdateEta(eta);
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { ParkingRepositoryLoader } from "./ParkingRepositoryLoader";
|
||||
import { ParkingGetterSetterRepository } from "../../repositories/parking/ParkingGetterSetterRepository";
|
||||
import { createHash } from "node:crypto";
|
||||
import { ApiResponseError } from "../ApiResponseError";
|
||||
import { IParkingStructure } from "../../entities/ParkingRepositoryEntities";
|
||||
|
||||
class ApiParseError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "ApiParseError";
|
||||
}
|
||||
}
|
||||
|
||||
export class ChapmanApiBasedParkingRepositoryLoader implements ParkingRepositoryLoader {
|
||||
public static readonly id = "chapman-parking-loader";
|
||||
private readonly fetchUrl = "https://webfarm.chapman.edu/ParkingService/ParkingService/counts";
|
||||
|
||||
constructor(
|
||||
public repository: ParkingGetterSetterRepository
|
||||
) {
|
||||
this.fetchAndUpdateParkingStructures = this.fetchAndUpdateParkingStructures.bind(this);
|
||||
}
|
||||
|
||||
async updateAll() {
|
||||
await this.fetchAndUpdateParkingStructures();
|
||||
}
|
||||
|
||||
async fetchAndUpdateParkingStructures(): Promise<void> {
|
||||
let json: any;
|
||||
|
||||
try {
|
||||
const response = await fetch(this.fetchUrl);
|
||||
json = await response.json();
|
||||
} catch(e: any) {
|
||||
throw new ApiResponseError(e.message);
|
||||
}
|
||||
|
||||
try {
|
||||
if (typeof json.Structures === "object") {
|
||||
const parkingStructures: IParkingStructure[] = json.Structures.map(this.constructIParkingStructureFromJson);
|
||||
|
||||
await Promise.all(parkingStructures.map(async (structure: IParkingStructure) => {
|
||||
await this.repository.addOrUpdateParkingStructure(structure);
|
||||
}));
|
||||
}
|
||||
} catch(e: any) {
|
||||
throw new ApiParseError(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
public constructIParkingStructureFromJson(jsonStructure: any) {
|
||||
const structureToReturn: IParkingStructure = {
|
||||
capacity: jsonStructure.Capacity,
|
||||
coordinates: {
|
||||
latitude: jsonStructure.Latitude,
|
||||
longitude: jsonStructure.Longitude,
|
||||
},
|
||||
id: ChapmanApiBasedParkingRepositoryLoader.generateId(jsonStructure.Address),
|
||||
name: jsonStructure.Name,
|
||||
spotsAvailable: jsonStructure.CurrentCount > jsonStructure.Capacity ? jsonStructure.Capacity : jsonStructure.CurrentCount,
|
||||
address: jsonStructure.Address,
|
||||
updatedTime: new Date(),
|
||||
}
|
||||
|
||||
return structureToReturn;
|
||||
}
|
||||
|
||||
private static normalizeAddress(address: string): string {
|
||||
return address
|
||||
.toLowerCase()
|
||||
.split(/\s+/)
|
||||
.filter(part => part.length > 0)
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
public static generateId(address: string): string {
|
||||
const normalized = this.normalizeAddress(address);
|
||||
const hash = createHash('sha256')
|
||||
.update(normalized)
|
||||
.digest('hex');
|
||||
|
||||
return hash.substring(0, 32);
|
||||
}
|
||||
}
|
||||
5
src/loaders/parking/ParkingRepositoryLoader.ts
Normal file
5
src/loaders/parking/ParkingRepositoryLoader.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
import { RepositoryLoader } from "../RepositoryLoader";
|
||||
|
||||
export interface ParkingRepositoryLoader extends RepositoryLoader {
|
||||
fetchAndUpdateParkingStructures(): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
import {
|
||||
ChapmanApiBasedParkingRepositoryLoader
|
||||
} from "../ChapmanApiBasedParkingRepositoryLoader";
|
||||
import { InMemoryParkingRepository } from "../../../repositories/parking/InMemoryParkingRepository";
|
||||
import {
|
||||
resetGlobalFetchMockJson,
|
||||
updateGlobalFetchMockJson,
|
||||
updateGlobalFetchMockJsonToThrowSyntaxError
|
||||
} from "../../../../testHelpers/fetchMockHelpers";
|
||||
import {
|
||||
chapmanParkingStructureData
|
||||
} from "../../../../testHelpers/jsonSnapshots/chapmanParkingStructureData/chapmanParkingStructureData";
|
||||
import { IParkingStructure } from "../../../entities/ParkingRepositoryEntities";
|
||||
import { assertAsyncCallbackThrowsApiResponseError } from "../../../../testHelpers/assertAsyncCallbackThrowsApiResponseError";
|
||||
|
||||
describe("ChapmanApiBasedParkingRepositoryLoader", () => {
|
||||
let loader: ChapmanApiBasedParkingRepositoryLoader;
|
||||
|
||||
beforeEach(() => {
|
||||
loader = new ChapmanApiBasedParkingRepositoryLoader(
|
||||
new InMemoryParkingRepository(),
|
||||
);
|
||||
resetGlobalFetchMockJson();
|
||||
});
|
||||
|
||||
describe("fetchAndUpdateAll", () => {
|
||||
it("calls all the correct methods", async () => {
|
||||
const spies = {
|
||||
fetchAndUpdateParkingStructures: jest.spyOn(loader, "fetchAndUpdateParkingStructures"),
|
||||
};
|
||||
|
||||
Object.values(spies).forEach((spy: any) => {
|
||||
spy.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
await loader.updateAll();
|
||||
|
||||
Object.values(spies).forEach((spy: any) => {
|
||||
expect(spy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("fetchAndUpdateParkingStructures", () => {
|
||||
it("fetches and update parking structures with unique IDs", async () => {
|
||||
updateGlobalFetchMockJson(chapmanParkingStructureData);
|
||||
|
||||
await loader.fetchAndUpdateParkingStructures();
|
||||
|
||||
let expectedStructures: IParkingStructure[] = [
|
||||
{
|
||||
address: "300 E Walnut, Orange, CA 92867",
|
||||
capacity: 871,
|
||||
spotsAvailable: 211,
|
||||
coordinates: {
|
||||
latitude: 33.7945513,
|
||||
longitude: -117.8518707,
|
||||
},
|
||||
name: "Anderson Structure",
|
||||
id: "",
|
||||
updatedTime: new Date(),
|
||||
},
|
||||
{
|
||||
address: "200 W Sycamore Ave, Orange, CA 92866-1053",
|
||||
capacity: 692,
|
||||
spotsAvailable: 282,
|
||||
coordinates: {
|
||||
latitude: 33.792937,
|
||||
longitude: -117.854782
|
||||
},
|
||||
name: "Barrera",
|
||||
id: "",
|
||||
updatedTime: new Date(),
|
||||
}
|
||||
];
|
||||
expectedStructures[0].id = ChapmanApiBasedParkingRepositoryLoader.generateId(expectedStructures[0].address);
|
||||
expectedStructures[1].id = ChapmanApiBasedParkingRepositoryLoader.generateId(expectedStructures[1].address);
|
||||
|
||||
const structuresFromLoader = await loader.repository.getParkingStructures();
|
||||
|
||||
// Set updatedTimeMs on expected data to avoid comparison
|
||||
expectedStructures[0].updatedTime = structuresFromLoader[0].updatedTime;
|
||||
expectedStructures[1].updatedTime = structuresFromLoader[1].updatedTime;
|
||||
|
||||
expect(structuresFromLoader).toEqual(expectedStructures);
|
||||
});
|
||||
|
||||
it("throws ApiResponseError if data is incorrect", async () => {
|
||||
updateGlobalFetchMockJsonToThrowSyntaxError();
|
||||
|
||||
await assertAsyncCallbackThrowsApiResponseError(async () => {
|
||||
await loader.fetchAndUpdateParkingStructures();
|
||||
});
|
||||
})
|
||||
});
|
||||
|
||||
describe("constructIParkingStructureFromJson", () => {
|
||||
it("normalizes the spots available if it's over the capacity", async () => {
|
||||
const sampleJsonStructure: any = {
|
||||
Capacity: 10,
|
||||
Latitude: 1,
|
||||
Longitude: 1,
|
||||
Address: "300 E Walnut, Orange, CA 92867",
|
||||
Name: "Anderson Structure",
|
||||
CurrentCount: 11,
|
||||
};
|
||||
|
||||
const returnedStructure = loader.constructIParkingStructureFromJson(sampleJsonStructure);
|
||||
expect(returnedStructure.spotsAvailable).toEqual(returnedStructure.capacity);
|
||||
});
|
||||
});
|
||||
});
|
||||
15
src/loaders/parking/buildParkingRepositoryLoaderIfExists.ts
Normal file
15
src/loaders/parking/buildParkingRepositoryLoaderIfExists.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { ParkingGetterSetterRepository } from "../../repositories/parking/ParkingGetterSetterRepository";
|
||||
import { ChapmanApiBasedParkingRepositoryLoader } from "./ChapmanApiBasedParkingRepositoryLoader";
|
||||
|
||||
export interface ParkingRepositoryLoaderBuilderArguments {
|
||||
id: string;
|
||||
repository: ParkingGetterSetterRepository;
|
||||
}
|
||||
|
||||
export function buildParkingRepositoryLoaderIfExists(args: ParkingRepositoryLoaderBuilderArguments) {
|
||||
if (args.id === ChapmanApiBasedParkingRepositoryLoader.id) {
|
||||
return new ChapmanApiBasedParkingRepositoryLoader(args.repository);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
35
src/loaders/parking/loadParkingTestData.ts
Normal file
35
src/loaders/parking/loadParkingTestData.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { ParkingGetterSetterRepository } from "../../repositories/parking/ParkingGetterSetterRepository";
|
||||
import { IParkingStructure } from "../../entities/ParkingRepositoryEntities";
|
||||
|
||||
const parkingStructures: IParkingStructure[] = [
|
||||
{
|
||||
address: "300 E Walnut, Orange, CA 92867",
|
||||
capacity: 871,
|
||||
spotsAvailable: 211,
|
||||
coordinates: {
|
||||
latitude: 33.7945513,
|
||||
longitude: -117.8518707,
|
||||
},
|
||||
name: "Anderson Structure",
|
||||
id: "1",
|
||||
updatedTime: new Date(),
|
||||
},
|
||||
{
|
||||
address: "200 W Sycamore Ave, Orange, CA 92866-1053",
|
||||
capacity: 692,
|
||||
spotsAvailable: 282,
|
||||
coordinates: {
|
||||
latitude: 33.792937,
|
||||
longitude: -117.854782
|
||||
},
|
||||
name: "Barrera",
|
||||
id: "2",
|
||||
updatedTime: new Date(),
|
||||
}
|
||||
];
|
||||
|
||||
export async function loadParkingTestData(repository: ParkingGetterSetterRepository) {
|
||||
await Promise.all(parkingStructures.map(async structure => {
|
||||
await repository.addOrUpdateParkingStructure(structure);
|
||||
}))
|
||||
}
|
||||
441
src/loaders/shuttle/ApiBasedShuttleRepositoryLoader.ts
Normal file
441
src/loaders/shuttle/ApiBasedShuttleRepositoryLoader.ts
Normal file
@@ -0,0 +1,441 @@
|
||||
import { ShuttleGetterSetterRepository } from "../../repositories/shuttle/ShuttleGetterSetterRepository";
|
||||
import { IEta, IRoute, IShuttle, IStop } from "../../entities/ShuttleRepositoryEntities";
|
||||
import { ShuttleRepositoryLoader } from "./ShuttleRepositoryLoader";
|
||||
import { ICoordinates, IEntityWithId } from "../../entities/SharedEntities";
|
||||
import { ApiResponseError } from "../ApiResponseError";
|
||||
import { SHUTTLE_TO_ROUTE_COORDINATE_MAXIMUM_DISTANCE_MILES } from "../../environment";
|
||||
import { ExternalSourceETARepository } from "../../repositories/shuttle/eta/ExternalSourceETARepository";
|
||||
|
||||
/**
|
||||
* Class which can load data into a repository from the
|
||||
* Passio Go API. Supports automatic pruning of all data types
|
||||
* which inherit from `IEntityWithId`.
|
||||
*/
|
||||
export class ApiBasedShuttleRepositoryLoader implements ShuttleRepositoryLoader {
|
||||
readonly baseUrl = "https://passiogo.com/mapGetData.php";
|
||||
|
||||
constructor(
|
||||
public passioSystemId: string,
|
||||
public systemIdForConstructedData: string,
|
||||
public shuttleRepository: ShuttleGetterSetterRepository,
|
||||
public etaRepository?: ExternalSourceETARepository,
|
||||
readonly shuttleToRouteCoordinateMaximumDistanceMiles = SHUTTLE_TO_ROUTE_COORDINATE_MAXIMUM_DISTANCE_MILES,
|
||||
) {
|
||||
}
|
||||
|
||||
private async constructExistingEntityIdSet<T extends IEntityWithId>(entitySearchCallback: () => Promise<T[]>) {
|
||||
const existingEntities = await entitySearchCallback();
|
||||
const ids = new Set<string>();
|
||||
existingEntities.forEach((entity) => {
|
||||
ids.add(entity.id);
|
||||
});
|
||||
return ids;
|
||||
}
|
||||
|
||||
public async updateAll() {
|
||||
await this.updateRouteDataForSystem();
|
||||
await this.updateStopAndPolylineDataForRoutesInSystem();
|
||||
await this.updateShuttleDataForSystemBasedOnProximityToRoutes();
|
||||
|
||||
if (this.etaRepository) {
|
||||
await this.updateEtaDataForExistingStopsForSystem();
|
||||
}
|
||||
}
|
||||
|
||||
public async updateRouteDataForSystem() {
|
||||
try {
|
||||
const json = await this.fetchRouteDataJson();
|
||||
const routes = this.constructRoutesFromJson(json);
|
||||
if (routes !== null) {
|
||||
await this.updateRouteDataInRepository(routes);
|
||||
} else {
|
||||
console.warn(`Route update failed for the following JSON: ${JSON.stringify(json)}`);
|
||||
}
|
||||
} catch(e: any) {
|
||||
throw new ApiResponseError(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
private async updateRouteDataInRepository(routes: IRoute[]) {
|
||||
const routeIdsToPrune = await this.constructExistingEntityIdSet(async () => {
|
||||
return await this.shuttleRepository.getRoutes();
|
||||
});
|
||||
|
||||
await Promise.all(routes.map(async (route) => {
|
||||
await this.shuttleRepository.addOrUpdateRoute(route);
|
||||
routeIdsToPrune.delete(route.id);
|
||||
}));
|
||||
|
||||
await Promise.all(Array.from(routeIdsToPrune).map(async (routeId) => {
|
||||
await this.shuttleRepository.removeRouteIfExists(routeId);
|
||||
}));
|
||||
}
|
||||
|
||||
private async fetchRouteDataJson() {
|
||||
const systemId = this.passioSystemId;
|
||||
|
||||
const params = {
|
||||
getRoutes: "2",
|
||||
};
|
||||
|
||||
const formDataJsonObject = {
|
||||
"systemSelected0": systemId,
|
||||
"amount": "1",
|
||||
};
|
||||
const formData = new FormData();
|
||||
formData.set("json", JSON.stringify(formDataJsonObject));
|
||||
|
||||
const query = new URLSearchParams(params).toString();
|
||||
|
||||
const response = await fetch(`${this.baseUrl}?${query}`, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
private constructRoutesFromJson(json: any): IRoute[] | null {
|
||||
if (typeof json.all === "object") {
|
||||
return json.all.map((jsonRoute: any) => {
|
||||
const constructedRoute: IRoute = {
|
||||
name: jsonRoute.name,
|
||||
color: jsonRoute.color,
|
||||
id: jsonRoute.myid,
|
||||
polylineCoordinates: [],
|
||||
systemId: this.systemIdForConstructedData,
|
||||
updatedTime: new Date(),
|
||||
};
|
||||
return constructedRoute;
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public async updateStopAndPolylineDataForRoutesInSystem() {
|
||||
try {
|
||||
const json = await this.fetchStopAndPolylineDataJson();
|
||||
await this.updateStopAndPolylineDataInRepository(json);
|
||||
} catch(e: any) {
|
||||
throw new ApiResponseError(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
private async updateStopAndPolylineDataInRepository(json: any) {
|
||||
const stopIdsToPrune = await this.constructExistingEntityIdSet(async () => {
|
||||
return await this.shuttleRepository.getStops();
|
||||
});
|
||||
|
||||
await this.updateStopDataForSystemAndApiResponse(json, stopIdsToPrune);
|
||||
await this.updateOrderedStopDataForExistingStops(json);
|
||||
await this.updatePolylineDataForExistingRoutesAndApiResponse(json);
|
||||
|
||||
await Promise.all(Array.from(stopIdsToPrune).map(async (stopId) => {
|
||||
await this.shuttleRepository.removeStopIfExists(stopId);
|
||||
}));
|
||||
}
|
||||
|
||||
private async fetchStopAndPolylineDataJson() {
|
||||
const passioSystemId = this.passioSystemId;
|
||||
|
||||
const params = {
|
||||
getStops: "2",
|
||||
};
|
||||
|
||||
const formDataJsonObject = {
|
||||
"s0": passioSystemId,
|
||||
"sA": 1
|
||||
};
|
||||
const formData = new FormData();
|
||||
formData.set("json", JSON.stringify(formDataJsonObject));
|
||||
|
||||
const query = new URLSearchParams(params).toString();
|
||||
|
||||
const response = await fetch(`${this.baseUrl}?${query}`, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
public async updateShuttleDataForSystemBasedOnProximityToRoutes() {
|
||||
try {
|
||||
const json = await this.fetchShuttleDataJson();
|
||||
let shuttles = this.constructInServiceShuttlesFromJson(json);
|
||||
if (shuttles !== null) {
|
||||
shuttles = await this.filterShuttlesByDistanceFromCorrespondingRoute(shuttles);
|
||||
await this.updateShuttleDataInRepository(shuttles);
|
||||
} else {
|
||||
console.warn(`Shuttle update failed for the following JSON: ${JSON.stringify(json)}`)
|
||||
}
|
||||
} catch(e: any) {
|
||||
throw new ApiResponseError(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
private async updateShuttleDataInRepository(shuttles: IShuttle[]) {
|
||||
const shuttleIdsToPrune = await this.constructExistingEntityIdSet(async () => {
|
||||
return await this.shuttleRepository.getShuttles();
|
||||
});
|
||||
|
||||
await Promise.all(shuttles.map(async (shuttle) => {
|
||||
await this.shuttleRepository.addOrUpdateShuttle(shuttle);
|
||||
shuttleIdsToPrune.delete(shuttle.id);
|
||||
}));
|
||||
|
||||
await Promise.all(Array.from(shuttleIdsToPrune).map(async (shuttleId) => {
|
||||
await this.shuttleRepository.removeShuttleIfExists(shuttleId);
|
||||
}));
|
||||
}
|
||||
|
||||
private async fetchShuttleDataJson() {
|
||||
const systemId = this.passioSystemId;
|
||||
|
||||
const params = {
|
||||
getBuses: "2"
|
||||
};
|
||||
|
||||
const formDataJsonObject = {
|
||||
"s0": systemId,
|
||||
"sA": "1"
|
||||
};
|
||||
|
||||
const formData = new FormData();
|
||||
formData.set("json", JSON.stringify(formDataJsonObject));
|
||||
|
||||
const query = new URLSearchParams(params).toString();
|
||||
|
||||
const response = await fetch(`${this.baseUrl}?${query}`, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
private constructInServiceShuttlesFromJson(json: any): IShuttle[] | null {
|
||||
if (json.buses && json.buses["-1"] === undefined) {
|
||||
const jsonBuses = Object.values(json.buses).map((busesArr: any) => {
|
||||
return busesArr[0];
|
||||
});
|
||||
jsonBuses.filter((bus) => bus.outOfService != 0)
|
||||
|
||||
return jsonBuses.map((jsonBus: any) => {
|
||||
const constructedShuttle: IShuttle = {
|
||||
name: jsonBus.bus,
|
||||
coordinates: {
|
||||
latitude: parseFloat(jsonBus.latitude),
|
||||
longitude: parseFloat(jsonBus.longitude),
|
||||
},
|
||||
routeId: jsonBus.routeId,
|
||||
systemId: this.systemIdForConstructedData,
|
||||
id: `${jsonBus.busId}`,
|
||||
orientationInDegrees: parseFloat(jsonBus.calculatedCourse),
|
||||
updatedTime: new Date(),
|
||||
}
|
||||
return constructedShuttle;
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public async updateEtaDataForExistingStopsForSystem() {
|
||||
const stops = await this.shuttleRepository.getStops();
|
||||
await Promise.all(stops.map(async (stop) => {
|
||||
let stopId = stop.id;
|
||||
await this.updateEtaDataForStopId(stopId);
|
||||
}));
|
||||
}
|
||||
|
||||
public async updateEtaDataForStopId(stopId: string) {
|
||||
try {
|
||||
const json = await this.fetchEtaDataJson(stopId);
|
||||
const etas = this.constructEtasFromJson(json, stopId);
|
||||
if (etas !== null) {
|
||||
await this.updateEtaDataInRepository(etas);
|
||||
} else {
|
||||
console.warn(`ETA update failed for stop ${stopId} with the following JSON: ${JSON.stringify(json)}`);
|
||||
}
|
||||
} catch(e: any) {
|
||||
throw new ApiResponseError(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
private async updateEtaDataInRepository(etas: IEta[]) {
|
||||
await Promise.all(etas.map(async (eta) => {
|
||||
await this.etaRepository?.addOrUpdateEtaFromExternalSource(eta);
|
||||
}));
|
||||
}
|
||||
|
||||
private async fetchEtaDataJson(stopId: string) {
|
||||
const params = {
|
||||
eta: "3",
|
||||
stopIds: stopId,
|
||||
};
|
||||
|
||||
const query = new URLSearchParams(params).toString();
|
||||
|
||||
const response = await fetch(`${this.baseUrl}?${query}`, {
|
||||
method: "GET",
|
||||
});
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
private constructEtasFromJson(json: any, stopId: string): IEta[] | null {
|
||||
if (json.ETAs && json.ETAs[stopId]) {
|
||||
return json.ETAs[stopId].map((jsonEta: any) => {
|
||||
const shuttleId: string = jsonEta.busId;
|
||||
const eta: IEta = {
|
||||
secondsRemaining: jsonEta.secondsSpent,
|
||||
shuttleId: `${shuttleId}`,
|
||||
stopId: stopId,
|
||||
updatedTime: new Date(),
|
||||
systemId: this.systemIdForConstructedData,
|
||||
};
|
||||
return eta;
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected async updateStopDataForSystemAndApiResponse(
|
||||
json: any,
|
||||
setOfIdsToPrune: Set<string> = new Set(),
|
||||
) {
|
||||
if (json.stops) {
|
||||
const jsonStops = Object.values(json.stops);
|
||||
|
||||
await Promise.all(jsonStops.map(async (stop: any) => {
|
||||
const constructedStop: IStop = {
|
||||
name: stop.name,
|
||||
id: stop.id,
|
||||
systemId: this.systemIdForConstructedData,
|
||||
coordinates: {
|
||||
latitude: parseFloat(stop.latitude),
|
||||
longitude: parseFloat(stop.longitude),
|
||||
},
|
||||
updatedTime: new Date(),
|
||||
};
|
||||
|
||||
await this.shuttleRepository.addOrUpdateStop(constructedStop);
|
||||
|
||||
setOfIdsToPrune.delete(constructedStop.id);
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
protected async updateOrderedStopDataForExistingStops(json: any) {
|
||||
if (json.routes) {
|
||||
await Promise.all(Object.keys(json.routes).map(async (routeId) => {
|
||||
const jsonOrderedStopData: any[][] = json.routes[routeId].slice(2);
|
||||
|
||||
// The API may return the same stop twice to indicate that
|
||||
// the route runs in a loop
|
||||
// If the API does not do this, assume the route is one-way
|
||||
// To account for this, check if ordered stop already exists in repo
|
||||
// If it does, write to that stop instead
|
||||
|
||||
for (let index = 0; index < jsonOrderedStopData.length; index++) {
|
||||
const orderedStopDataArray = jsonOrderedStopData[index];
|
||||
|
||||
const stopId = orderedStopDataArray[1];
|
||||
let constructedOrderedStop = await this.shuttleRepository.getOrderedStopByRouteAndStopId(routeId, stopId)
|
||||
if (constructedOrderedStop === null) {
|
||||
constructedOrderedStop = {
|
||||
routeId,
|
||||
stopId,
|
||||
position: index + 1,
|
||||
systemId: this.systemIdForConstructedData,
|
||||
updatedTime: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
if (index >= 1) {
|
||||
constructedOrderedStop.previousStop = {
|
||||
routeId,
|
||||
stopId: jsonOrderedStopData[index - 1][1],
|
||||
position: index,
|
||||
systemId: this.systemIdForConstructedData,
|
||||
updatedTime: new Date(),
|
||||
};
|
||||
}
|
||||
if (index < jsonOrderedStopData.length - 1) {
|
||||
constructedOrderedStop.nextStop = {
|
||||
routeId,
|
||||
stopId: jsonOrderedStopData[index + 1][1],
|
||||
position: index + 2,
|
||||
systemId: this.systemIdForConstructedData,
|
||||
updatedTime: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
await this.shuttleRepository.addOrUpdateOrderedStop(constructedOrderedStop);
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
protected async updatePolylineDataForExistingRoutesAndApiResponse(json: any) {
|
||||
if (json.routePoints) {
|
||||
await Promise.all(Object.keys(json.routePoints).map(async (routeId) => {
|
||||
const routePoints = json.routePoints[routeId][0];
|
||||
|
||||
const existingRoute = await this.shuttleRepository.getRouteById(routeId);
|
||||
if (!existingRoute) return;
|
||||
|
||||
existingRoute.polylineCoordinates = routePoints.map((point: any) => {
|
||||
return {
|
||||
latitude: parseFloat(point.lat),
|
||||
longitude: parseFloat(point.lng),
|
||||
};
|
||||
});
|
||||
|
||||
await this.shuttleRepository.addOrUpdateRoute(existingRoute);
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
private filterShuttlesByDistanceFromCorrespondingRoute = async (shuttles: IShuttle[]) => {
|
||||
let filteredShuttles: IShuttle[] = [];
|
||||
|
||||
await Promise.all(shuttles.map(async (shuttle) => {
|
||||
const route = await this.shuttleRepository.getRouteById(shuttle.routeId);
|
||||
if (route != null) {
|
||||
let closestDistanceMiles = Number.MAX_VALUE;
|
||||
|
||||
route.polylineCoordinates.forEach((coordinate) => {
|
||||
const calculatedDistance = ApiBasedShuttleRepositoryLoader.convertDistanceBetweenCoordinatesToMiles(coordinate, shuttle.coordinates)
|
||||
if (closestDistanceMiles > calculatedDistance) {
|
||||
closestDistanceMiles = calculatedDistance;
|
||||
}
|
||||
});
|
||||
|
||||
if (closestDistanceMiles <= this.shuttleToRouteCoordinateMaximumDistanceMiles) {
|
||||
filteredShuttles.push(shuttle);
|
||||
}
|
||||
} else {
|
||||
console.warn(`No corresponding route found for ID ${shuttle.routeId} of shuttle ${shuttle.id}`)
|
||||
}
|
||||
}));
|
||||
|
||||
return filteredShuttles;
|
||||
};
|
||||
|
||||
public static convertDistanceBetweenCoordinatesToMiles = (fromCoordinate: ICoordinates, toCoordinate: ICoordinates): number => {
|
||||
const earthRadiusMiles = 3959;
|
||||
|
||||
const lat1Rad = fromCoordinate.latitude * Math.PI / 180;
|
||||
const lat2Rad = toCoordinate.latitude * Math.PI / 180;
|
||||
const deltaLatRad = (toCoordinate.latitude - fromCoordinate.latitude) * Math.PI / 180;
|
||||
const deltaLonRad = (toCoordinate.longitude - fromCoordinate.longitude) * Math.PI / 180;
|
||||
|
||||
const a = Math.sin(deltaLatRad / 2) * Math.sin(deltaLatRad / 2) +
|
||||
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
|
||||
Math.sin(deltaLonRad / 2) * Math.sin(deltaLonRad / 2);
|
||||
|
||||
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||
|
||||
return earthRadiusMiles * c;
|
||||
};
|
||||
}
|
||||
9
src/loaders/shuttle/ShuttleRepositoryLoader.ts
Normal file
9
src/loaders/shuttle/ShuttleRepositoryLoader.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { RepositoryLoader } from "../RepositoryLoader";
|
||||
|
||||
export interface ShuttleRepositoryLoader extends RepositoryLoader {
|
||||
updateRouteDataForSystem(): Promise<void>;
|
||||
updateStopAndPolylineDataForRoutesInSystem(): Promise<void>;
|
||||
updateShuttleDataForSystemBasedOnProximityToRoutes(): Promise<void>;
|
||||
updateEtaDataForExistingStopsForSystem(): Promise<void>;
|
||||
updateEtaDataForStopId(stopId: string): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
import { ApiBasedShuttleRepositoryLoader } from "../ApiBasedShuttleRepositoryLoader";
|
||||
import { UnoptimizedInMemoryShuttleRepository } from "../../../repositories/shuttle/UnoptimizedInMemoryShuttleRepository";
|
||||
import { fetchRouteDataSuccessfulResponse } from "../../../../testHelpers/jsonSnapshots/fetchRouteData/fetchRouteDataSuccessfulResponse";
|
||||
import {
|
||||
fetchStopAndPolylineDataSuccessfulResponse
|
||||
} from "../../../../testHelpers/jsonSnapshots/fetchStopAndPolylineData/fetchStopAndPolylineDataSuccessfulResponse";
|
||||
import { generateMockRoutes, generateMockShuttles, generateMockStops } from "../../../../testHelpers/mockDataGenerators";
|
||||
import {
|
||||
fetchShuttleDataSuccessfulResponse
|
||||
} from "../../../../testHelpers/jsonSnapshots/fetchShuttleData/fetchShuttleDataSuccessfulResponse";
|
||||
import { InMemoryExternalSourceETARepository } from "../../../repositories/shuttle/eta/InMemoryExternalSourceETARepository";
|
||||
import {
|
||||
resetGlobalFetchMockJson,
|
||||
updateGlobalFetchMockJson,
|
||||
updateGlobalFetchMockJsonToThrowSyntaxError
|
||||
} from "../../../../testHelpers/fetchMockHelpers";
|
||||
import { assertAsyncCallbackThrowsApiResponseError } from "../../../../testHelpers/assertAsyncCallbackThrowsApiResponseError";
|
||||
import { IRoute } from "../../../entities/ShuttleRepositoryEntities";
|
||||
|
||||
describe("ApiBasedShuttleRepositoryLoader", () => {
|
||||
let loader: ApiBasedShuttleRepositoryLoader;
|
||||
|
||||
beforeEach(() => {
|
||||
loader = new ApiBasedShuttleRepositoryLoader("263", "1", new UnoptimizedInMemoryShuttleRepository());
|
||||
resetGlobalFetchMockJson();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
const systemId = "1";
|
||||
|
||||
describe("updateAll", () => {
|
||||
it("calls all the correct methods", async () => {
|
||||
const spies = {
|
||||
updateRouteDataForSystem: jest.spyOn(loader, "updateRouteDataForSystem"),
|
||||
updateStopAndPolylineDataForRoutesInSystem: jest.spyOn(loader, "updateStopAndPolylineDataForRoutesInSystem"),
|
||||
updateShuttleDataForSystem: jest.spyOn(loader, "updateShuttleDataForSystemBasedOnProximityToRoutes"),
|
||||
};
|
||||
|
||||
Object.values(spies).forEach((spy: any) => {
|
||||
spy.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
await loader.updateAll();
|
||||
|
||||
Object.values(spies).forEach((spy: any) => {
|
||||
expect(spy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateRouteDataForSystem", () => {
|
||||
it("updates route data in repository if response received", async () => {
|
||||
// Arrange
|
||||
// Test pruning
|
||||
const routesToPrune = generateMockRoutes();
|
||||
await Promise.all(routesToPrune.map(async (route) => {
|
||||
route.systemId = systemId;
|
||||
await loader.shuttleRepository.addOrUpdateRoute(route);
|
||||
}));
|
||||
|
||||
updateGlobalFetchMockJson(fetchRouteDataSuccessfulResponse);
|
||||
|
||||
// Act
|
||||
await loader.updateRouteDataForSystem();
|
||||
|
||||
// Assert
|
||||
const routes = await loader.shuttleRepository.getRoutes();
|
||||
|
||||
expect(routes.length).toEqual(fetchRouteDataSuccessfulResponse.all.length)
|
||||
});
|
||||
|
||||
it("throws the correct error if the API response contains no data", async () => {
|
||||
// The Passio API returns some invalid JSON if there is no data,
|
||||
// so simulate a JSON parsing error
|
||||
|
||||
updateGlobalFetchMockJsonToThrowSyntaxError();
|
||||
|
||||
await assertAsyncCallbackThrowsApiResponseError(async () => {
|
||||
await loader.updateRouteDataForSystem();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateStopAndPolylineDataForRoutesInSystem", () => {
|
||||
it("updates stop and polyline data if response received", async () => {
|
||||
// Arrange
|
||||
// Test pruning of stops only
|
||||
const stopsToPrune = generateMockStops();
|
||||
await Promise.all(stopsToPrune.map(async (stop) => {
|
||||
stop.systemId = systemId;
|
||||
await loader.shuttleRepository.addOrUpdateStop(stop);
|
||||
}));
|
||||
|
||||
updateGlobalFetchMockJson(fetchStopAndPolylineDataSuccessfulResponse);
|
||||
|
||||
const stopsArray = Object.values(fetchStopAndPolylineDataSuccessfulResponse.stops);
|
||||
|
||||
await loader.updateStopAndPolylineDataForRoutesInSystem();
|
||||
|
||||
const stops = await loader.shuttleRepository.getStops();
|
||||
expect(stops.length).toEqual(stopsArray.length);
|
||||
|
||||
await Promise.all(stops.map(async (stop) => {
|
||||
const orderedStops = await loader.shuttleRepository.getOrderedStopsByStopId(stop.id)
|
||||
expect(orderedStops.length).toBeGreaterThan(0);
|
||||
}));
|
||||
|
||||
const routes = await loader.shuttleRepository.getRoutes();
|
||||
routes.forEach((route) => {
|
||||
expect(route.polylineCoordinates.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
it("throws the correct error if the API response contains no data", async () => {
|
||||
updateGlobalFetchMockJsonToThrowSyntaxError();
|
||||
|
||||
await assertAsyncCallbackThrowsApiResponseError(async () => {
|
||||
await loader.updateStopAndPolylineDataForRoutesInSystem();
|
||||
});
|
||||
})
|
||||
});
|
||||
|
||||
describe("updateShuttleDataForSystemBasedOnProximityToRoutes", () => {
|
||||
function generateMockRoutesWithPolylineCoordinates() {
|
||||
const routes = generateMockRoutes();
|
||||
routes[0].polylineCoordinates = [
|
||||
{latitude: 33.78792, longitude: -117.86187},
|
||||
{latitude: 33.78792, longitude: -117.86200},
|
||||
{latitude: 33.78792, longitude: -117.86245}
|
||||
];
|
||||
return routes;
|
||||
}
|
||||
|
||||
function getMockJsonResponseMatchingRouteAndCoordinates(route: IRoute, longitude: string, latitude: string) {
|
||||
const modifiedSuccessfulResponse = {
|
||||
...fetchShuttleDataSuccessfulResponse,
|
||||
};
|
||||
|
||||
Object.keys(modifiedSuccessfulResponse.buses).forEach((busId) => {
|
||||
const bus = (modifiedSuccessfulResponse.buses as any)[busId][0];
|
||||
bus.latitude = latitude;
|
||||
bus.longitude = longitude;
|
||||
bus.routeId = route.id;
|
||||
});
|
||||
return modifiedSuccessfulResponse;
|
||||
}
|
||||
|
||||
async function addMockRoutes(routes: IRoute[]) {
|
||||
await Promise.all(routes.map(async (route) => {
|
||||
await loader.shuttleRepository.addOrUpdateRoute(route);
|
||||
}));
|
||||
}
|
||||
|
||||
it("updates shuttle data in repository from API if shuttles close enough to route", async () => {
|
||||
const distanceMiles = 1;
|
||||
loader = new ApiBasedShuttleRepositoryLoader(
|
||||
"263",
|
||||
"1",
|
||||
new UnoptimizedInMemoryShuttleRepository(),
|
||||
new InMemoryExternalSourceETARepository(),
|
||||
distanceMiles,
|
||||
);
|
||||
|
||||
const routes = generateMockRoutesWithPolylineCoordinates();
|
||||
await addMockRoutes(routes);
|
||||
const modifiedSuccessfulResponse = getMockJsonResponseMatchingRouteAndCoordinates(
|
||||
routes[0],
|
||||
"-117.86187",
|
||||
"33.78792"
|
||||
);
|
||||
updateGlobalFetchMockJson(modifiedSuccessfulResponse);
|
||||
const busesInResponse = Object.values(modifiedSuccessfulResponse.buses);
|
||||
|
||||
await loader.updateShuttleDataForSystemBasedOnProximityToRoutes();
|
||||
|
||||
const shuttles = await loader.shuttleRepository.getShuttles();
|
||||
expect(shuttles.length).toEqual(busesInResponse.length);
|
||||
});
|
||||
|
||||
it("does not update shuttle data in repository from API if shuttles are not close enough to route", async () => {
|
||||
const distanceMiles = 1;
|
||||
loader = new ApiBasedShuttleRepositoryLoader(
|
||||
"263",
|
||||
"1",
|
||||
new UnoptimizedInMemoryShuttleRepository(),
|
||||
new InMemoryExternalSourceETARepository(),
|
||||
distanceMiles,
|
||||
);
|
||||
|
||||
const routes = generateMockRoutesWithPolylineCoordinates();
|
||||
await addMockRoutes(routes);
|
||||
|
||||
const modifiedSuccessfulResponse = getMockJsonResponseMatchingRouteAndCoordinates(
|
||||
routes[0],
|
||||
"-116.86187",
|
||||
"32.78792"
|
||||
);
|
||||
updateGlobalFetchMockJson(modifiedSuccessfulResponse);
|
||||
|
||||
await loader.updateShuttleDataForSystemBasedOnProximityToRoutes();
|
||||
|
||||
const shuttles = await loader.shuttleRepository.getShuttles();
|
||||
expect(shuttles.length).toEqual(0);
|
||||
});
|
||||
|
||||
it("prunes shuttles correctly", async () => {
|
||||
const distanceMiles = 1;
|
||||
loader = new ApiBasedShuttleRepositoryLoader(
|
||||
"263",
|
||||
"1",
|
||||
new UnoptimizedInMemoryShuttleRepository(),
|
||||
new InMemoryExternalSourceETARepository(),
|
||||
distanceMiles,
|
||||
);
|
||||
|
||||
// Add mock shuttles to repository (these should be pruned)
|
||||
const shuttlesToPrune = generateMockShuttles();
|
||||
await Promise.all(shuttlesToPrune.map(async (shuttle) => {
|
||||
shuttle.systemId = systemId;
|
||||
await loader.shuttleRepository.addOrUpdateShuttle(shuttle);
|
||||
}));
|
||||
|
||||
const routes = generateMockRoutesWithPolylineCoordinates();
|
||||
await addMockRoutes(routes);
|
||||
|
||||
const modifiedSuccessfulResponse = getMockJsonResponseMatchingRouteAndCoordinates(
|
||||
routes[0],
|
||||
"-117.86187",
|
||||
"33.78792"
|
||||
);
|
||||
|
||||
updateGlobalFetchMockJson(modifiedSuccessfulResponse);
|
||||
|
||||
// Update shuttles from API
|
||||
await loader.updateShuttleDataForSystemBasedOnProximityToRoutes();
|
||||
|
||||
// Old shuttles should be pruned, only API shuttles should remain
|
||||
const shuttles = await loader.shuttleRepository.getShuttles();
|
||||
const busesInResponse = Object.values(modifiedSuccessfulResponse.buses);
|
||||
|
||||
expect(shuttles.length).toEqual(busesInResponse.length);
|
||||
|
||||
// Verify none of the original mock shuttles remain
|
||||
shuttlesToPrune.forEach((originalShuttle) => {
|
||||
const foundShuttle = shuttles.find(s => s.id === originalShuttle.id);
|
||||
expect(foundShuttle).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
it("throws the correct error if the API response contains no data", async () => {
|
||||
updateGlobalFetchMockJsonToThrowSyntaxError();
|
||||
|
||||
await assertAsyncCallbackThrowsApiResponseError(async () => {
|
||||
await loader.updateShuttleDataForSystemBasedOnProximityToRoutes();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
101
src/notifications/schedulers/ETANotificationScheduler.ts
Normal file
101
src/notifications/schedulers/ETANotificationScheduler.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import { IEta } from "../../entities/ShuttleRepositoryEntities";
|
||||
import { AppleNotificationSender, NotificationAlertArguments } from "../senders/AppleNotificationSender";
|
||||
import {
|
||||
NotificationRepository,
|
||||
ScheduledNotification
|
||||
} from "../../repositories/notifications/NotificationRepository";
|
||||
import { InMemoryNotificationRepository } from "../../repositories/notifications/InMemoryNotificationRepository";
|
||||
import { ETAGetterRepository, ETARepositoryEvent } from "../../repositories/shuttle/eta/ETAGetterRepository";
|
||||
import { ShuttleGetterRepository } from "../../repositories/shuttle/ShuttleGetterRepository";
|
||||
|
||||
export class ETANotificationScheduler {
|
||||
public static readonly defaultSecondsThresholdForNotificationToFire = 180;
|
||||
|
||||
constructor(
|
||||
private etaRepository: ETAGetterRepository,
|
||||
private shuttleRepository: ShuttleGetterRepository,
|
||||
private notificationRepository: NotificationRepository = new InMemoryNotificationRepository(),
|
||||
private appleNotificationSender = new AppleNotificationSender(),
|
||||
private interchangeSystemId: string,
|
||||
) {
|
||||
this.etaSubscriberCallback = this.etaSubscriberCallback.bind(this);
|
||||
this.sendEtaNotificationImmediately = this.sendEtaNotificationImmediately.bind(this);
|
||||
this.sendEtaNotificationImmediatelyIfSecondsRemainingBelowThreshold = this.sendEtaNotificationImmediatelyIfSecondsRemainingBelowThreshold.bind(this);
|
||||
}
|
||||
|
||||
private async sendEtaNotificationImmediately(notificationData: ScheduledNotification): Promise<boolean> {
|
||||
const { deviceId, shuttleId, stopId } = notificationData;
|
||||
|
||||
const shuttle = await this.shuttleRepository.getShuttleById(shuttleId);
|
||||
const stop = await this.shuttleRepository.getStopById(stopId);
|
||||
const eta = await this.etaRepository.getEtaForShuttleAndStopId(shuttleId, stopId);
|
||||
if (!shuttle) {
|
||||
console.warn(`Notification ${notificationData} fell through; no associated shuttle`);
|
||||
return false;
|
||||
}
|
||||
if (!stop) {
|
||||
console.warn(`Notification ${notificationData} fell through; no associated stop`);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Notification may not be sent if ETA is unavailable at the moment;
|
||||
// this is fine because it will be sent again when ETA becomes available
|
||||
if (!eta) {
|
||||
console.warn(`Notification ${notificationData} fell through; no associated ETA`);
|
||||
return false;
|
||||
}
|
||||
|
||||
const notificationAlertArguments: NotificationAlertArguments = {
|
||||
title: "Shuttle is arriving",
|
||||
body: `Shuttle is approaching ${stop.name} in ${Math.ceil(eta.secondsRemaining / 60)} minutes.`,
|
||||
customKeys: {
|
||||
shuttleEtaNotificationInfo: {
|
||||
shuttleId,
|
||||
stopId,
|
||||
systemId: this.interchangeSystemId,
|
||||
}
|
||||
},
|
||||
}
|
||||
return this.appleNotificationSender.sendNotificationImmediately(deviceId, notificationAlertArguments);
|
||||
}
|
||||
|
||||
private async etaSubscriberCallback(eta: IEta) {
|
||||
const deviceIdsToRemove = new Set<string>();
|
||||
const notifications = await this.notificationRepository.getAllNotificationsForShuttleAndStopId(
|
||||
eta.shuttleId,
|
||||
eta.stopId
|
||||
)
|
||||
|
||||
for (let notification of notifications) {
|
||||
const deliveredSuccessfully = await this.sendEtaNotificationImmediatelyIfSecondsRemainingBelowThreshold(notification, eta.secondsRemaining);
|
||||
if (deliveredSuccessfully) {
|
||||
deviceIdsToRemove.add(notification.deviceId);
|
||||
}
|
||||
}
|
||||
|
||||
deviceIdsToRemove.forEach((deviceId) => {
|
||||
this.notificationRepository.deleteNotificationIfExists({
|
||||
shuttleId: eta.shuttleId,
|
||||
stopId: eta.stopId,
|
||||
deviceId,
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
private async sendEtaNotificationImmediatelyIfSecondsRemainingBelowThreshold(notificationObject: ScheduledNotification, etaSecondsRemaining: number) {
|
||||
if (etaSecondsRemaining > notificationObject.secondsThreshold) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return await this.sendEtaNotificationImmediately(notificationObject);
|
||||
}
|
||||
|
||||
// The following is a workaround for the constructor being called twice
|
||||
public startListeningForUpdates() {
|
||||
this.etaRepository.on(ETARepositoryEvent.ETA_UPDATED, this.etaSubscriberCallback);
|
||||
}
|
||||
|
||||
public stopListeningForUpdates() {
|
||||
this.etaRepository.off(ETARepositoryEvent.ETA_UPDATED, this.etaSubscriberCallback);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
import { ETANotificationScheduler } from "../ETANotificationScheduler";
|
||||
import { UnoptimizedInMemoryShuttleRepository } from "../../../repositories/shuttle/UnoptimizedInMemoryShuttleRepository";
|
||||
import { InMemoryExternalSourceETARepository } from "../../../repositories/shuttle/eta/InMemoryExternalSourceETARepository";
|
||||
import { IEta, IShuttle, IStop } from "../../../entities/ShuttleRepositoryEntities";
|
||||
import { addMockShuttleToRepository, addMockStopToRepository } from "../../../../testHelpers/repositorySetupHelpers";
|
||||
import { AppleNotificationSender } from "../../senders/AppleNotificationSender";
|
||||
import { InMemoryNotificationRepository } from "../../../repositories/notifications/InMemoryNotificationRepository";
|
||||
import { NotificationRepository } from "../../../repositories/notifications/NotificationRepository";
|
||||
|
||||
jest.mock("http2");
|
||||
jest.mock("../../senders/AppleNotificationSender");
|
||||
|
||||
const MockAppleNotificationSender = AppleNotificationSender as jest.MockedClass<typeof AppleNotificationSender>;
|
||||
|
||||
function mockNotificationSenderMethods(shouldSimulateNotificationSend: boolean) {
|
||||
MockAppleNotificationSender.prototype.sendNotificationImmediately = jest.fn(async () => shouldSimulateNotificationSend);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for a specified number of milliseconds.
|
||||
* @param ms
|
||||
*/
|
||||
async function waitForMilliseconds(ms: number): Promise<void> {
|
||||
await new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
|
||||
describe("ETANotificationScheduler", () => {
|
||||
let shuttleRepository: UnoptimizedInMemoryShuttleRepository;
|
||||
let etaRepository: InMemoryExternalSourceETARepository;
|
||||
let notificationService: ETANotificationScheduler;
|
||||
let notificationRepository: NotificationRepository;
|
||||
|
||||
beforeEach(() => {
|
||||
shuttleRepository = new UnoptimizedInMemoryShuttleRepository();
|
||||
notificationRepository = new InMemoryNotificationRepository();
|
||||
etaRepository = new InMemoryExternalSourceETARepository();
|
||||
|
||||
mockNotificationSenderMethods(true);
|
||||
|
||||
const appleNotificationSender = new MockAppleNotificationSender(false);
|
||||
notificationService = new ETANotificationScheduler(
|
||||
etaRepository,
|
||||
shuttleRepository,
|
||||
notificationRepository,
|
||||
appleNotificationSender,
|
||||
"1",
|
||||
);
|
||||
notificationService.startListeningForUpdates();
|
||||
});
|
||||
|
||||
function generateNotificationDataAndEta(shuttle: IShuttle, stop: IStop) {
|
||||
const eta: IEta = {
|
||||
shuttleId: shuttle.id,
|
||||
stopId: stop.id,
|
||||
secondsRemaining: 120,
|
||||
systemId: "1",
|
||||
updatedTime: new Date(),
|
||||
};
|
||||
|
||||
const notificationData1 = {
|
||||
deviceId: "1",
|
||||
shuttleId: eta.shuttleId,
|
||||
stopId: eta.stopId,
|
||||
secondsThreshold: 240,
|
||||
}
|
||||
const notificationData2 = {
|
||||
...notificationData1,
|
||||
deviceId: "2",
|
||||
secondsThreshold: 180,
|
||||
}
|
||||
return { eta, notificationData1, notificationData2 };
|
||||
}
|
||||
|
||||
describe("etaSubscriberCallback", () => {
|
||||
it("sends and clears correct notification after ETA changed", async () => {
|
||||
// Arrange
|
||||
const shuttle = await addMockShuttleToRepository(shuttleRepository, "1");
|
||||
const stop = await addMockStopToRepository(shuttleRepository, "1");
|
||||
|
||||
const { eta, notificationData1, notificationData2 } = generateNotificationDataAndEta(shuttle, stop);
|
||||
|
||||
// Act
|
||||
await notificationRepository.addOrUpdateNotification(notificationData1);
|
||||
await notificationRepository.addOrUpdateNotification(notificationData2);
|
||||
await etaRepository.addOrUpdateEtaFromExternalSource(eta);
|
||||
|
||||
// Assert
|
||||
// Wait for the callback to actually be called
|
||||
await waitForMilliseconds(1000);
|
||||
|
||||
const isFirstNotificationScheduled = await notificationRepository.isNotificationScheduled(notificationData1);
|
||||
const isSecondNotificationScheduled = await notificationRepository.isNotificationScheduled(notificationData2);
|
||||
|
||||
// No longer scheduled after being sent
|
||||
expect(isFirstNotificationScheduled).toBe(false);
|
||||
expect(isSecondNotificationScheduled).toBe(false);
|
||||
});
|
||||
|
||||
it("doesn't send notification if seconds threshold not exceeded", async () => {
|
||||
// Arrange
|
||||
const shuttle = await addMockShuttleToRepository(shuttleRepository, "1");
|
||||
const stop = await addMockStopToRepository(shuttleRepository, "1");
|
||||
const { eta, notificationData1 } = generateNotificationDataAndEta(shuttle, stop);
|
||||
notificationData1.secondsThreshold = eta.secondsRemaining - 10;
|
||||
|
||||
// Act
|
||||
await notificationRepository.addOrUpdateNotification(notificationData1);
|
||||
await etaRepository.addOrUpdateEtaFromExternalSource(eta);
|
||||
|
||||
// Assert
|
||||
await waitForMilliseconds(500);
|
||||
const isNotificationScheduled = await notificationRepository.isNotificationScheduled(notificationData1);
|
||||
expect(isNotificationScheduled).toBe(true);
|
||||
});
|
||||
|
||||
it("leaves notification in array if delivery unsuccessful", async () => {
|
||||
// Arrange
|
||||
const shuttle = await addMockShuttleToRepository(shuttleRepository, "1");
|
||||
const stop = await addMockStopToRepository(shuttleRepository, "1");
|
||||
const { eta, notificationData1 } = generateNotificationDataAndEta(shuttle, stop)
|
||||
|
||||
// replace the old notification scheduler with a new one
|
||||
// detach the old callback method from the shuttle repo
|
||||
notificationService.stopListeningForUpdates();
|
||||
|
||||
// replace the notification repository with a fresh one too
|
||||
const notificationRepository = new InMemoryNotificationRepository();
|
||||
|
||||
mockNotificationSenderMethods(false);
|
||||
const updatedNotificationSender = new MockAppleNotificationSender(false);
|
||||
notificationService = new ETANotificationScheduler(
|
||||
etaRepository,
|
||||
shuttleRepository,
|
||||
notificationRepository,
|
||||
updatedNotificationSender,
|
||||
"1",
|
||||
);
|
||||
notificationService.startListeningForUpdates();
|
||||
|
||||
// Act
|
||||
await notificationRepository.addOrUpdateNotification(notificationData1);
|
||||
await etaRepository.addOrUpdateEtaFromExternalSource(eta);
|
||||
|
||||
// Assert
|
||||
// The notification should stay scheduled to be retried once
|
||||
// the ETA updates again
|
||||
await waitForMilliseconds(500);
|
||||
const isNotificationScheduled = await notificationRepository.isNotificationScheduled(notificationData1);
|
||||
expect(isNotificationScheduled).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
192
src/notifications/senders/AppleNotificationSender.ts
Normal file
192
src/notifications/senders/AppleNotificationSender.ts
Normal file
@@ -0,0 +1,192 @@
|
||||
import jwt from "jsonwebtoken";
|
||||
import http2 from "http2";
|
||||
import { ClientHttp2Session } from "node:http2";
|
||||
|
||||
interface APNsUrl {
|
||||
fullUrl: string;
|
||||
path: string;
|
||||
host: string;
|
||||
}
|
||||
|
||||
export interface NotificationAlertArguments {
|
||||
title: string;
|
||||
body: string;
|
||||
customKeys?: any,
|
||||
}
|
||||
|
||||
export class AppleNotificationSender {
|
||||
private apnsToken: string | undefined = undefined;
|
||||
private _lastRefreshedTimeMs: Date | undefined = undefined;
|
||||
|
||||
constructor(
|
||||
private shouldActuallySendNotifications = true,
|
||||
private client: ClientHttp2Session | undefined = undefined,
|
||||
) {
|
||||
this.sendNotificationImmediately = this.sendNotificationImmediately.bind(this);
|
||||
this.lastReloadedTimeForAPNsIsTooRecent = this.lastReloadedTimeForAPNsIsTooRecent.bind(this);
|
||||
this.reloadAPNsTokenIfTimePassed = this.reloadAPNsTokenIfTimePassed.bind(this);
|
||||
this.openConnectionIfNoneExists = this.openConnectionIfNoneExists.bind(this);
|
||||
this.closeConnectionIfExists = this.closeConnectionIfExists.bind(this);
|
||||
this.registerClosureEventsForClient = this.registerClosureEventsForClient.bind(this);
|
||||
|
||||
if (this.client !== undefined) {
|
||||
this.registerClosureEventsForClient();
|
||||
}
|
||||
}
|
||||
|
||||
get lastRefreshedTimeMs(): Date | undefined {
|
||||
return this._lastRefreshedTimeMs;
|
||||
}
|
||||
|
||||
private lastReloadedTimeForAPNsIsTooRecent() {
|
||||
const thirtyMinutesMs = 1800000;
|
||||
return this._lastRefreshedTimeMs && Date.now() - this._lastRefreshedTimeMs.getTime() < thirtyMinutesMs;
|
||||
}
|
||||
|
||||
public reloadAPNsTokenIfTimePassed() {
|
||||
if (this.lastReloadedTimeForAPNsIsTooRecent()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const keyId = process.env.APNS_KEY_ID;
|
||||
const teamId = process.env.APNS_TEAM_ID;
|
||||
|
||||
const privateKeyBase64 = process.env.APNS_PRIVATE_KEY;
|
||||
if (!privateKeyBase64) return;
|
||||
const privateKey = Buffer.from(privateKeyBase64, 'base64').toString('utf-8');
|
||||
|
||||
const tokenHeader = {
|
||||
alg: "ES256",
|
||||
"kid": keyId,
|
||||
};
|
||||
|
||||
const nowMs = Date.now();
|
||||
const claimsPayload = {
|
||||
"iss": teamId,
|
||||
"iat": Math.ceil(nowMs / 1000), // APNs requires number of seconds since Epoch
|
||||
};
|
||||
|
||||
this.apnsToken = jwt.sign(claimsPayload, privateKey, {
|
||||
algorithm: "ES256",
|
||||
header: tokenHeader
|
||||
});
|
||||
this._lastRefreshedTimeMs = new Date(nowMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a notification immediately.
|
||||
* @param deviceId
|
||||
* @param notificationAlertArguments
|
||||
*
|
||||
* @return Boolean promise indicating whether the
|
||||
* notification was sent successfully.
|
||||
*/
|
||||
public async sendNotificationImmediately(deviceId: string, notificationAlertArguments: NotificationAlertArguments) {
|
||||
if (!this.shouldActuallySendNotifications) {
|
||||
// pretend that the notification sent
|
||||
return true;
|
||||
}
|
||||
|
||||
this.reloadAPNsTokenIfTimePassed();
|
||||
|
||||
const bundleId = process.env.APNS_BUNDLE_ID;
|
||||
if (typeof bundleId !== "string") {
|
||||
throw new Error("APNS_BUNDLE_ID environment variable is not set correctly");
|
||||
}
|
||||
|
||||
this.openConnectionIfNoneExists();
|
||||
|
||||
const { path } = AppleNotificationSender.getAPNsFullUrlToUse(deviceId);
|
||||
|
||||
const headers = {
|
||||
':method': 'POST',
|
||||
':path': path,
|
||||
'authorization': `bearer ${this.apnsToken}`,
|
||||
"apns-push-type": "alert",
|
||||
"apns-expiration": "0",
|
||||
"apns-priority": "10",
|
||||
"apns-topic": bundleId,
|
||||
};
|
||||
try {
|
||||
if (!this.client) { return false }
|
||||
const req = this.client.request(headers);
|
||||
req.setEncoding('utf8');
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
req.on('response', (headers, _flags) => {
|
||||
if (headers[":status"] !== 200) {
|
||||
reject(`APNs request failed with status ${headers[":status"]}`);
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
|
||||
const customKeys = {
|
||||
...notificationAlertArguments.customKeys,
|
||||
}
|
||||
delete notificationAlertArguments.customKeys;
|
||||
|
||||
// See https://developer.apple.com/documentation/usernotifications/generating-a-remote-notification
|
||||
// for notification payload examples
|
||||
const payload = JSON.stringify({
|
||||
aps: {
|
||||
alert: notificationAlertArguments,
|
||||
sound: "default"
|
||||
},
|
||||
...customKeys,
|
||||
});
|
||||
req.write(payload);
|
||||
req.end();
|
||||
});
|
||||
return true;
|
||||
} catch(e) {
|
||||
console.error(e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private openConnectionIfNoneExists() {
|
||||
const host = AppleNotificationSender.getAPNsHostToUse();
|
||||
|
||||
if (!this.client) {
|
||||
this.client = http2.connect(host);
|
||||
this.registerClosureEventsForClient();
|
||||
}
|
||||
}
|
||||
|
||||
private registerClosureEventsForClient() {
|
||||
this.client?.on('close', this.closeConnectionIfExists);
|
||||
this.client?.on('error', this.closeConnectionIfExists);
|
||||
this.client?.on('goaway', this.closeConnectionIfExists);
|
||||
this.client?.on('timeout', this.closeConnectionIfExists);
|
||||
}
|
||||
|
||||
private closeConnectionIfExists() {
|
||||
this.client?.close();
|
||||
this.client = undefined;
|
||||
}
|
||||
|
||||
public static getAPNsFullUrlToUse(deviceId: string): APNsUrl {
|
||||
let hostToUse = this.getAPNsHostToUse();
|
||||
|
||||
const path = "/3/device/" + deviceId;
|
||||
const fullUrl = hostToUse + path;
|
||||
|
||||
return {
|
||||
fullUrl,
|
||||
host: hostToUse,
|
||||
path,
|
||||
};
|
||||
}
|
||||
|
||||
public static getAPNsHostToUse() {
|
||||
// Construct the fetch request
|
||||
const devBaseUrl = "https://api.development.push.apple.com"
|
||||
const prodBaseUrl = "https://api.push.apple.com"
|
||||
|
||||
let hostToUse = devBaseUrl;
|
||||
if (process.env.APNS_IS_PRODUCTION === "1") {
|
||||
hostToUse = prodBaseUrl;
|
||||
}
|
||||
return hostToUse;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
import http2 from "http2";
|
||||
import { EventEmitter } from "node:events";
|
||||
import {
|
||||
AppleNotificationSender,
|
||||
NotificationAlertArguments
|
||||
} from "../AppleNotificationSender";
|
||||
import { ClientHttp2Session } from "node:http2";
|
||||
|
||||
jest.mock("http2");
|
||||
|
||||
const sampleKeyBase64 = "LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JR1RBZ0VBTUJNR0J5cUdTTTQ5QWdFR0NDcUdTTTQ5QXdFSEJIa3dkd0lCQVFRZ3NybVNBWklhZ09mQ1A4c0IKV2kyQ0JYRzFPbzd2MWJpc3BJWkN3SXI0UkRlZ0NnWUlLb1pJemowREFRZWhSQU5DQUFUWkh4VjJ3UUpMTUJxKwp5YSt5ZkdpM2cyWlV2NmhyZmUrajA4eXRla1BIalhTMHF6Sm9WRUx6S0hhNkVMOVlBb1pEWEJ0QjZoK2ZHaFhlClNPY09OYmFmCi0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS0K";
|
||||
|
||||
class MockClient extends EventEmitter {
|
||||
constructor(
|
||||
private status: number,
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
request = jest.fn((_) => {
|
||||
const mockRequest: any = new EventEmitter();
|
||||
mockRequest.setEncoding = jest.fn();
|
||||
mockRequest.write = jest.fn();
|
||||
mockRequest.end = jest.fn(() => {
|
||||
setTimeout(() => {
|
||||
mockRequest.emit('response', { ':status': this.status });
|
||||
}, 10);
|
||||
});
|
||||
return mockRequest;
|
||||
});
|
||||
|
||||
close = jest.fn(() => {});
|
||||
}
|
||||
|
||||
function mockHttp2Connect(status: number) {
|
||||
(http2.connect as jest.Mock) = jest.fn(() => new MockClient(status));
|
||||
}
|
||||
|
||||
describe("AppleNotificationSender", () => {
|
||||
let notificationSender: AppleNotificationSender;
|
||||
|
||||
beforeEach(() => {
|
||||
notificationSender = new AppleNotificationSender();
|
||||
|
||||
// Ensure that tests don't hit the server
|
||||
process.env = {
|
||||
...process.env,
|
||||
APNS_KEY_ID: "1",
|
||||
APNS_TEAM_ID: "1",
|
||||
APNS_BUNDLE_ID: "dev.bchen.ProjectInter",
|
||||
APNS_PRIVATE_KEY: sampleKeyBase64,
|
||||
};
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
mockHttp2Connect(200);
|
||||
});
|
||||
|
||||
describe("reloadAPNsTokenIfTimePassed", () => {
|
||||
it("reloads the token if token hasn't been generated yet", async () => {
|
||||
notificationSender.reloadAPNsTokenIfTimePassed();
|
||||
expect(notificationSender.lastRefreshedTimeMs).toBeDefined();
|
||||
});
|
||||
|
||||
it("doesn't reload the token if last refreshed time is recent", async () => {
|
||||
notificationSender.reloadAPNsTokenIfTimePassed();
|
||||
const lastRefreshedTimeMs = notificationSender.lastRefreshedTimeMs;
|
||||
|
||||
notificationSender.reloadAPNsTokenIfTimePassed();
|
||||
// Expect no change to have occurred
|
||||
expect(lastRefreshedTimeMs).toEqual(notificationSender.lastRefreshedTimeMs);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAPNsFullUrlToUse', () => {
|
||||
it('should return the production URL when APNS_IS_PRODUCTION is set to "1"', () => {
|
||||
process.env.APNS_IS_PRODUCTION = "1";
|
||||
const deviceId = 'testDeviceId';
|
||||
const result = AppleNotificationSender.getAPNsFullUrlToUse(deviceId);
|
||||
|
||||
const { fullUrl, host, path } = result;
|
||||
expect(fullUrl).toBe(`https://api.push.apple.com/3/device/${deviceId}`);
|
||||
expect(host).toBe("https://api.push.apple.com");
|
||||
expect(path).toBe(`/3/device/${deviceId}`);
|
||||
});
|
||||
|
||||
it('should return the sandbox URL when APNS_IS_PRODUCTION is set to something other than 1', () => {
|
||||
process.env.APNS_IS_PRODUCTION = "0";
|
||||
const deviceId = 'testDeviceId';
|
||||
const result = AppleNotificationSender.getAPNsFullUrlToUse(deviceId);
|
||||
|
||||
const { fullUrl, host, path } = result;
|
||||
expect(fullUrl).toBe(`https://api.development.push.apple.com/3/device/${deviceId}`);
|
||||
expect(host).toBe("https://api.development.push.apple.com");
|
||||
expect(path).toBe(`/3/device/${deviceId}`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendNotificationImmediately", () => {
|
||||
it('makes the connection to the http server if sending a notification for the first time', async () => {
|
||||
const notificationArguments: NotificationAlertArguments = {
|
||||
title: 'Test notification',
|
||||
body: 'This notification will send',
|
||||
}
|
||||
|
||||
const result = await notificationSender.sendNotificationImmediately('1', notificationArguments);
|
||||
|
||||
expect(http2.connect).toHaveBeenCalled();
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('reuses the existing connection if sending another notification', async () => {
|
||||
const notificationArguments: NotificationAlertArguments = {
|
||||
title: 'Test notification',
|
||||
body: 'This notification will send',
|
||||
}
|
||||
|
||||
const result1 = await notificationSender.sendNotificationImmediately('1', notificationArguments);
|
||||
const result2 = await notificationSender.sendNotificationImmediately('1', notificationArguments);
|
||||
|
||||
expect(http2.connect).toHaveBeenCalledTimes(1);
|
||||
expect(result1).toBe(true);
|
||||
expect(result2).toBe(true);
|
||||
});
|
||||
|
||||
it('throws an error if the bundle ID is not set correctly', async () => {
|
||||
process.env = {
|
||||
...process.env,
|
||||
APNS_BUNDLE_ID: undefined,
|
||||
}
|
||||
const notificationArguments: NotificationAlertArguments = {
|
||||
title: 'Test notification',
|
||||
body: 'This notification will not send',
|
||||
}
|
||||
|
||||
await expect(async () => {
|
||||
await notificationSender.sendNotificationImmediately('1', notificationArguments);
|
||||
}).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('returns false if there is an error sending the notification', async () => {
|
||||
mockHttp2Connect(403);
|
||||
|
||||
const notificationArguments: NotificationAlertArguments = {
|
||||
title: 'Test notification',
|
||||
body: 'This notification will not send',
|
||||
}
|
||||
|
||||
const result = await notificationSender.sendNotificationImmediately('1', notificationArguments);
|
||||
|
||||
expect(http2.connect).toHaveBeenCalled();
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('does not send notification if shouldActuallySendNotifications is false', async () => {
|
||||
notificationSender = new AppleNotificationSender(false);
|
||||
|
||||
const notificationArguments: NotificationAlertArguments = {
|
||||
title: 'Test notification',
|
||||
body: 'This notification should not send',
|
||||
}
|
||||
|
||||
const result = await notificationSender.sendNotificationImmediately('1', notificationArguments);
|
||||
|
||||
expect(http2.connect).not.toHaveBeenCalled();
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it("registers a handler to close the connection if `close` event fired", async () => {
|
||||
const connectionCloseEvents = ['close', 'goaway', 'error', 'timeout'];
|
||||
|
||||
await Promise.all(connectionCloseEvents.map(async (event) => {
|
||||
const mockClient = new MockClient(200);
|
||||
notificationSender = new AppleNotificationSender(true, mockClient as unknown as ClientHttp2Session);
|
||||
|
||||
const notificationArguments: NotificationAlertArguments = {
|
||||
title: 'Test notification',
|
||||
body: ''
|
||||
};
|
||||
|
||||
await notificationSender.sendNotificationImmediately('1', notificationArguments);
|
||||
|
||||
mockClient.emit(event);
|
||||
|
||||
expect(mockClient.close).toHaveBeenCalled();
|
||||
}));
|
||||
});
|
||||
});
|
||||
});
|
||||
29
src/repositories/BaseRedisRepository.ts
Normal file
29
src/repositories/BaseRedisRepository.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { RedisClientType } from 'redis';
|
||||
import { EventEmitter } from 'stream';
|
||||
import createRedisClientForRepository from '../helpers/createRedisClientForRepository';
|
||||
|
||||
export abstract class BaseRedisRepository extends EventEmitter {
|
||||
protected redisClient;
|
||||
|
||||
constructor(
|
||||
redisClient: RedisClientType = createRedisClientForRepository(),
|
||||
) {
|
||||
super();
|
||||
this.redisClient = redisClient;
|
||||
this.redisClient.on('error', (err) => {
|
||||
console.error(err.stack);
|
||||
});
|
||||
}
|
||||
|
||||
get isReady() {
|
||||
return this.redisClient.isReady;
|
||||
}
|
||||
|
||||
public async connect() {
|
||||
await this.redisClient.connect();
|
||||
}
|
||||
|
||||
public async disconnect() {
|
||||
await this.redisClient.disconnect();
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import { IEta, IOrderedStop, IRoute, IShuttle, IStop, ISystem } from "../entities/entities";
|
||||
|
||||
export interface GetterRepository {
|
||||
getSystems(): Promise<ISystem[]>;
|
||||
getSystemById(systemId: string): Promise<ISystem | null>;
|
||||
|
||||
getStopsBySystemId(systemId: string): Promise<IStop[]>;
|
||||
getStopById(stopId: string): Promise<IStop | null>;
|
||||
|
||||
getRoutesBySystemId(systemId: string): Promise<IRoute[]>;
|
||||
getRouteById(routeId: string): Promise<IRoute | null>;
|
||||
|
||||
getShuttlesBySystemId(systemId: string): Promise<IShuttle[]>;
|
||||
getShuttleById(shuttleId: string): Promise<IShuttle | null>;
|
||||
getShuttlesByRouteId(routeId: string): Promise<IShuttle[]>;
|
||||
|
||||
getEtasForShuttleId(shuttleId: string): Promise<IEta[]>;
|
||||
getEtasForStopId(stopId: string): Promise<IEta[]>;
|
||||
|
||||
getEtaForShuttleAndStopId(shuttleId: string, stopId: string): Promise<IEta | null>;
|
||||
|
||||
getOrderedStopByRouteAndStopId(routeId: string, stopId: string): Promise<IOrderedStop | null>;
|
||||
|
||||
/**
|
||||
* Get ordered stops with the given stop ID.
|
||||
* Returns an empty array if no ordered stops found.
|
||||
* @param stopId
|
||||
*/
|
||||
getOrderedStopsByStopId(stopId: string): Promise<IOrderedStop[]>;
|
||||
|
||||
/**
|
||||
* Get ordered stops with the given route ID.
|
||||
* Returns an empty array if no ordered stops found.
|
||||
* @param routeId
|
||||
*/
|
||||
getOrderedStopsByRouteId(routeId: string): Promise<IOrderedStop[]>;
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
// If types match closely, we can use TypeScript "casting"
|
||||
// to convert from data repo to GraphQL schema
|
||||
|
||||
import { GetterRepository } from "./GetterRepository";
|
||||
import { IEta, IOrderedStop, IRoute, IShuttle, IStop, ISystem } from "../entities/entities";
|
||||
|
||||
/**
|
||||
* GetterRepository interface for data derived from Passio API.
|
||||
* The repository is not designed to have write locks in place.
|
||||
* Objects passed from/to the repository should be treated
|
||||
* as disposable.
|
||||
*/
|
||||
export interface GetterSetterRepository extends GetterRepository {
|
||||
// Setter methods
|
||||
addOrUpdateSystem(system: ISystem): Promise<void>;
|
||||
addOrUpdateRoute(route: IRoute): Promise<void>;
|
||||
addOrUpdateShuttle(shuttle: IShuttle): Promise<void>;
|
||||
addOrUpdateStop(stop: IStop): Promise<void>;
|
||||
addOrUpdateOrderedStop(orderedStop: IOrderedStop): Promise<void>;
|
||||
addOrUpdateEta(eta: IEta): Promise<void>;
|
||||
|
||||
removeSystemIfExists(systemId: string): Promise<ISystem | null>;
|
||||
removeRouteIfExists(routeId: string): Promise<IRoute | null>;
|
||||
removeShuttleIfExists(shuttleId: string): Promise<IShuttle | null>;
|
||||
removeStopIfExists(stopId: string): Promise<IStop | null>;
|
||||
removeOrderedStopIfExists(stopId: string, routeId: string): Promise<IOrderedStop | null>;
|
||||
removeEtaIfExists(shuttleId: string, stopId: string): Promise<IEta | null>;
|
||||
|
||||
clearSystemData(): Promise<void>;
|
||||
clearRouteData(): Promise<void>;
|
||||
clearShuttleData(): Promise<void>;
|
||||
clearStopData(): Promise<void>;
|
||||
clearOrderedStopData(): Promise<void>;
|
||||
clearEtaData(): Promise<void>;
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
import { GetterSetterRepository } from "./GetterSetterRepository";
|
||||
import { IEntityWithId, IEta, IOrderedStop, IRoute, IShuttle, IStop, ISystem } from "../entities/entities";
|
||||
|
||||
/**
|
||||
* An unoptimized in memory repository.
|
||||
* (I would optimize it with actual data structures, but I'm
|
||||
* switching to another data store later anyways)
|
||||
*/
|
||||
export class UnoptimizedInMemoryRepository implements GetterSetterRepository {
|
||||
private systems: ISystem[] = [];
|
||||
private stops: IStop[] = [];
|
||||
private routes: IRoute[] = [];
|
||||
private shuttles: IShuttle[] = [];
|
||||
private etas: IEta[] = [];
|
||||
private orderedStops: IOrderedStop[] = [];
|
||||
|
||||
public async getSystems() {
|
||||
return this.systems;
|
||||
}
|
||||
|
||||
public async getSystemById(systemId: string) {
|
||||
return this.findEntityById(systemId, this.systems);
|
||||
}
|
||||
|
||||
public async getStopsBySystemId(systemId: string) {
|
||||
return this.stops.filter(stop => stop.systemId === systemId);
|
||||
}
|
||||
|
||||
public async getStopById(stopId: string) {
|
||||
return this.findEntityById(stopId, this.stops);
|
||||
}
|
||||
|
||||
public async getRoutesBySystemId(systemId: string) {
|
||||
return this.routes.filter(route => route.systemId === systemId);
|
||||
}
|
||||
|
||||
public async getRouteById(routeId: string) {
|
||||
return this.findEntityById(routeId, this.routes);
|
||||
}
|
||||
|
||||
public async getShuttlesBySystemId(systemId: string) {
|
||||
return this.shuttles.filter(shuttle => shuttle.systemId === systemId);
|
||||
}
|
||||
|
||||
public async getShuttlesByRouteId(routeId: string) {
|
||||
return this.shuttles.filter(shuttle => shuttle.routeId === routeId);
|
||||
}
|
||||
|
||||
public async getShuttleById(shuttleId: string) {
|
||||
return this.findEntityById(shuttleId, this.shuttles);
|
||||
}
|
||||
|
||||
public async getEtasForShuttleId(shuttleId: string) {
|
||||
return this.etas.filter(eta => eta.shuttleId === shuttleId);
|
||||
}
|
||||
|
||||
public async getEtasForStopId(stopId: string) {
|
||||
return this.etas.filter(eta => eta.stopId === stopId);
|
||||
}
|
||||
|
||||
public async getEtaForShuttleAndStopId(shuttleId: string, stopId: string) {
|
||||
return this.findEntityByMatcher<IEta>((value) => value.stopId === stopId && value.shuttleId === shuttleId, this.etas);
|
||||
}
|
||||
|
||||
public async getOrderedStopByRouteAndStopId(routeId: string, stopId: string) {
|
||||
return this.findEntityByMatcher<IOrderedStop>((value) => value.routeId === routeId && value.stopId === stopId, this.orderedStops)
|
||||
}
|
||||
|
||||
public async getOrderedStopsByStopId(stopId: string) {
|
||||
return this.orderedStops.filter((value) => value.stopId === stopId);
|
||||
}
|
||||
|
||||
public async getOrderedStopsByRouteId(routeId: string) {
|
||||
return this.orderedStops.filter((value) => value.routeId === routeId);
|
||||
}
|
||||
|
||||
private findEntityById<T extends IEntityWithId>(entityId: string, arrayToSearchIn: T[]) {
|
||||
return this.findEntityByMatcher((value) => value.id === entityId, arrayToSearchIn);
|
||||
}
|
||||
|
||||
private findEntityByMatcher<T>(callback: (value: T) => boolean, arrayToSearchIn: T[]): T | null {
|
||||
const entity = arrayToSearchIn.find(callback);
|
||||
if (!entity) {
|
||||
return null;
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
public async addOrUpdateSystem(system: ISystem): Promise<void> {
|
||||
const index = this.systems.findIndex((s) => s.id === system.id);
|
||||
if (index !== -1) {
|
||||
this.systems[index] = system; // Update existing
|
||||
} else {
|
||||
this.systems.push(system); // Add new
|
||||
}
|
||||
}
|
||||
|
||||
public async addOrUpdateRoute(route: IRoute): Promise<void> {
|
||||
const index = this.routes.findIndex((r) => r.id === route.id);
|
||||
if (index !== -1) {
|
||||
this.routes[index] = route;
|
||||
} else {
|
||||
this.routes.push(route);
|
||||
}
|
||||
}
|
||||
|
||||
public async addOrUpdateShuttle(shuttle: IShuttle): Promise<void> {
|
||||
const index = this.shuttles.findIndex((s) => s.id === shuttle.id);
|
||||
if (index !== -1) {
|
||||
this.shuttles[index] = shuttle;
|
||||
} else {
|
||||
this.shuttles.push(shuttle);
|
||||
}
|
||||
}
|
||||
|
||||
public async addOrUpdateStop(stop: IStop): Promise<void> {
|
||||
const index = this.stops.findIndex((s) => s.id === stop.id);
|
||||
if (index !== -1) {
|
||||
this.stops[index] = stop;
|
||||
} else {
|
||||
this.stops.push(stop);
|
||||
}
|
||||
}
|
||||
|
||||
public async addOrUpdateOrderedStop(orderedStop: IOrderedStop): Promise<void> {
|
||||
const index = this.orderedStops.findIndex((value) => value.stopId === orderedStop.stopId && value.routeId === orderedStop.routeId);
|
||||
if (index !== -1) {
|
||||
this.orderedStops[index] = orderedStop;
|
||||
} else {
|
||||
this.orderedStops.push(orderedStop);
|
||||
}
|
||||
}
|
||||
|
||||
public async addOrUpdateEta(eta: IEta): Promise<void> {
|
||||
const index = this.etas.findIndex((e) => e.stopId === eta.stopId && e.shuttleId === eta.shuttleId);
|
||||
if (index !== -1) {
|
||||
this.etas[index] = eta;
|
||||
} else {
|
||||
this.etas.push(eta);
|
||||
}
|
||||
}
|
||||
|
||||
private async removeEntityByMatcherIfExists<T>(callback: (value: T) => boolean, arrayToSearchIn: T[]) {
|
||||
const index = arrayToSearchIn.findIndex(callback);
|
||||
if (index > -1) {
|
||||
const entityToReturn = arrayToSearchIn[index];
|
||||
arrayToSearchIn.splice(index, 1);
|
||||
return entityToReturn;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private async removeEntityByIdIfExists<T extends IEntityWithId>(entityId: string, arrayToSearchIn: T[]) {
|
||||
return await this.removeEntityByMatcherIfExists((value) => value.id === entityId, arrayToSearchIn);
|
||||
}
|
||||
|
||||
public async removeSystemIfExists(systemId: string): Promise<ISystem | null> {
|
||||
return await this.removeEntityByIdIfExists(systemId, this.systems);
|
||||
}
|
||||
|
||||
public async removeRouteIfExists(routeId: string): Promise<IRoute | null> {
|
||||
return await this.removeEntityByIdIfExists(routeId, this.routes);
|
||||
}
|
||||
|
||||
public async removeShuttleIfExists(shuttleId: string): Promise<IShuttle | null> {
|
||||
return await this.removeEntityByIdIfExists(shuttleId, this.shuttles);
|
||||
}
|
||||
|
||||
public async removeStopIfExists(stopId: string): Promise<IStop | null> {
|
||||
return await this.removeEntityByIdIfExists(stopId, this.stops);
|
||||
}
|
||||
|
||||
public async removeOrderedStopIfExists(stopId: string, routeId: string): Promise<IOrderedStop | null> {
|
||||
return await this.removeEntityByMatcherIfExists((orderedStop) => {
|
||||
return orderedStop.stopId === stopId
|
||||
&& orderedStop.routeId === routeId
|
||||
}, this.orderedStops);
|
||||
}
|
||||
|
||||
public async removeEtaIfExists(shuttleId: string, stopId: string): Promise<IEta | null> {
|
||||
return await this.removeEntityByMatcherIfExists((eta) => {
|
||||
return eta.stopId === stopId
|
||||
&& eta.shuttleId === shuttleId
|
||||
}, this.etas);
|
||||
}
|
||||
|
||||
public async clearSystemData() {
|
||||
this.systems = [];
|
||||
}
|
||||
|
||||
public async clearShuttleData(): Promise<void> {
|
||||
this.shuttles = [];
|
||||
}
|
||||
|
||||
public async clearEtaData(): Promise<void> {
|
||||
this.etas = [];
|
||||
}
|
||||
|
||||
public async clearOrderedStopData(): Promise<void> {
|
||||
this.orderedStops = [];
|
||||
}
|
||||
|
||||
public async clearRouteData(): Promise<void> {
|
||||
this.routes = [];
|
||||
}
|
||||
|
||||
public async clearStopData(): Promise<void> {
|
||||
this.stops = [];
|
||||
}
|
||||
|
||||
}
|
||||
144
src/repositories/notifications/InMemoryNotificationRepository.ts
Normal file
144
src/repositories/notifications/InMemoryNotificationRepository.ts
Normal file
@@ -0,0 +1,144 @@
|
||||
import {
|
||||
Listener,
|
||||
NotificationEvent,
|
||||
NotificationLookupArguments,
|
||||
NotificationRepository,
|
||||
ScheduledNotification
|
||||
} from "./NotificationRepository";
|
||||
import { TupleKey } from "../../types/TupleKey";
|
||||
|
||||
type DeviceIdSecondsThresholdAssociation = { [key: string]: number };
|
||||
|
||||
export class InMemoryNotificationRepository implements NotificationRepository {
|
||||
/**
|
||||
* An object of device ID arrays to deliver notifications to.
|
||||
* The key should be a combination of the shuttle ID and
|
||||
* stop ID, which can be generated using `TupleKey`.
|
||||
* The value is a dictionary of the device ID to the stored seconds threshold.
|
||||
* @private
|
||||
*/
|
||||
private deviceIdsToDeliverTo: { [key: string]: DeviceIdSecondsThresholdAssociation } = {}
|
||||
|
||||
private listeners: Listener[] = [];
|
||||
|
||||
constructor() {
|
||||
this.getAllNotificationsForShuttleAndStopId = this.getAllNotificationsForShuttleAndStopId.bind(this);
|
||||
this.getSecondsThresholdForNotificationIfExists = this.getSecondsThresholdForNotificationIfExists.bind(this);
|
||||
this.deleteNotificationIfExists = this.deleteNotificationIfExists.bind(this);
|
||||
this.addOrUpdateNotification = this.addOrUpdateNotification.bind(this);
|
||||
this.isNotificationScheduled = this.isNotificationScheduled.bind(this);
|
||||
this.subscribeToNotificationChanges = this.subscribeToNotificationChanges.bind(this);
|
||||
this.unsubscribeFromNotificationChanges = this.unsubscribeFromNotificationChanges.bind(this);
|
||||
}
|
||||
|
||||
async getAllNotificationsForShuttleAndStopId(shuttleId: string, stopId: string) {
|
||||
const tuple = new TupleKey(shuttleId, stopId);
|
||||
if (this.deviceIdsToDeliverTo[tuple.toString()] === undefined) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Object.keys(this.deviceIdsToDeliverTo[tuple.toString()])
|
||||
.map((deviceId) => {
|
||||
return {
|
||||
shuttleId,
|
||||
stopId,
|
||||
deviceId,
|
||||
secondsThreshold: this.deviceIdsToDeliverTo[tuple.toString()][deviceId]
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async getSecondsThresholdForNotificationIfExists({
|
||||
shuttleId,
|
||||
stopId,
|
||||
deviceId
|
||||
}: NotificationLookupArguments) {
|
||||
const tuple = new TupleKey(shuttleId, stopId);
|
||||
if (this.deviceIdsToDeliverTo[tuple.toString()] === undefined) {
|
||||
return null;
|
||||
}
|
||||
return this.deviceIdsToDeliverTo[tuple.toString()][deviceId];
|
||||
}
|
||||
|
||||
async isNotificationScheduled(lookupArguments: NotificationLookupArguments): Promise<boolean> {
|
||||
const threshold = await this.getSecondsThresholdForNotificationIfExists(lookupArguments);
|
||||
return threshold !== null;
|
||||
}
|
||||
|
||||
async addOrUpdateNotification({
|
||||
shuttleId,
|
||||
stopId,
|
||||
deviceId,
|
||||
secondsThreshold
|
||||
}: ScheduledNotification) {
|
||||
const tuple = new TupleKey(shuttleId, stopId);
|
||||
if (this.deviceIdsToDeliverTo[tuple.toString()] === undefined) {
|
||||
this.deviceIdsToDeliverTo[tuple.toString()] = {};
|
||||
}
|
||||
|
||||
this.deviceIdsToDeliverTo[tuple.toString()][deviceId] = secondsThreshold;
|
||||
this.listeners.forEach((listener: Listener) => {
|
||||
const event: NotificationEvent = {
|
||||
event: 'addOrUpdate',
|
||||
notification: {
|
||||
shuttleId,
|
||||
stopId,
|
||||
deviceId,
|
||||
secondsThreshold
|
||||
},
|
||||
}
|
||||
|
||||
listener(event);
|
||||
})
|
||||
}
|
||||
|
||||
async deleteNotificationIfExists({
|
||||
deviceId,
|
||||
shuttleId,
|
||||
stopId
|
||||
}: NotificationLookupArguments) {
|
||||
const tupleKey = new TupleKey(shuttleId, stopId);
|
||||
if (
|
||||
this.deviceIdsToDeliverTo[tupleKey.toString()] === undefined
|
||||
|| !(deviceId in this.deviceIdsToDeliverTo[tupleKey.toString()])
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const secondsThreshold = this.deviceIdsToDeliverTo[tupleKey.toString()][deviceId];
|
||||
delete this.deviceIdsToDeliverTo[tupleKey.toString()][deviceId];
|
||||
|
||||
if (Object.keys(this.deviceIdsToDeliverTo[tupleKey.toString()]).length === 0) {
|
||||
// no more device IDs remaining for this key combination
|
||||
delete this.deviceIdsToDeliverTo[tupleKey.toString()];
|
||||
}
|
||||
|
||||
this.listeners.forEach((listener) => {
|
||||
const event: NotificationEvent = {
|
||||
event: 'delete',
|
||||
notification: {
|
||||
deviceId,
|
||||
shuttleId,
|
||||
stopId,
|
||||
secondsThreshold
|
||||
}
|
||||
}
|
||||
|
||||
listener(event);
|
||||
})
|
||||
}
|
||||
|
||||
public subscribeToNotificationChanges(listener: Listener): void {
|
||||
const index = this.listeners.findIndex((existingListener) => existingListener == listener);
|
||||
if (index < 0) {
|
||||
this.listeners.push(listener);
|
||||
}
|
||||
}
|
||||
|
||||
public unsubscribeFromNotificationChanges(listener: Listener): void {
|
||||
const index = this.listeners.findIndex((existingListener) => existingListener == listener);
|
||||
if (index >= 0) {
|
||||
this.listeners.splice(index, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
33
src/repositories/notifications/NotificationRepository.ts
Normal file
33
src/repositories/notifications/NotificationRepository.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
export interface NotificationLookupArguments {
|
||||
deviceId: string;
|
||||
shuttleId: string;
|
||||
stopId: string;
|
||||
}
|
||||
|
||||
export interface ScheduledNotification extends NotificationLookupArguments {
|
||||
/**
|
||||
* Value which specifies the ETA of the shuttle for when
|
||||
* the notification should fire.
|
||||
* For example, a secondsThreshold of 180 would mean that the notification
|
||||
* fires when the ETA drops below 3 minutes.
|
||||
*/
|
||||
secondsThreshold: number;
|
||||
}
|
||||
|
||||
export type Listener = ((event: NotificationEvent) => any);
|
||||
|
||||
export interface NotificationEvent {
|
||||
notification: ScheduledNotification,
|
||||
event: 'delete' | 'addOrUpdate'
|
||||
}
|
||||
|
||||
export interface NotificationRepository {
|
||||
getAllNotificationsForShuttleAndStopId(shuttleId: string, stopId: string): Promise<ScheduledNotification[]>;
|
||||
getSecondsThresholdForNotificationIfExists(lookupArguments: NotificationLookupArguments): Promise<number | null>;
|
||||
isNotificationScheduled(lookupArguments: NotificationLookupArguments): Promise<boolean>;
|
||||
addOrUpdateNotification(notification: ScheduledNotification): Promise<void>;
|
||||
deleteNotificationIfExists(lookupArguments: NotificationLookupArguments): Promise<void>;
|
||||
|
||||
subscribeToNotificationChanges(listener: Listener): void;
|
||||
unsubscribeFromNotificationChanges(listener: Listener): void;
|
||||
}
|
||||
113
src/repositories/notifications/RedisNotificationRepository.ts
Normal file
113
src/repositories/notifications/RedisNotificationRepository.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
import { TupleKey } from '../../types/TupleKey';
|
||||
import {
|
||||
Listener,
|
||||
NotificationEvent,
|
||||
NotificationLookupArguments,
|
||||
NotificationRepository,
|
||||
ScheduledNotification
|
||||
} from "./NotificationRepository";
|
||||
import { BaseRedisRepository } from "../BaseRedisRepository";
|
||||
|
||||
export class RedisNotificationRepository extends BaseRedisRepository implements NotificationRepository {
|
||||
private notificationListeners: Listener[] = [];
|
||||
private readonly NOTIFICATION_KEY_PREFIX = 'notification:';
|
||||
|
||||
private getNotificationKey = (shuttleId: string, stopId: string): string => {
|
||||
const tuple = new TupleKey(shuttleId, stopId);
|
||||
return `${this.NOTIFICATION_KEY_PREFIX}${tuple.toString()}`;
|
||||
};
|
||||
|
||||
public addOrUpdateNotification = async (notification: ScheduledNotification): Promise<void> => {
|
||||
const { shuttleId, stopId, deviceId, secondsThreshold } = notification;
|
||||
const key = this.getNotificationKey(shuttleId, stopId);
|
||||
|
||||
await this.redisClient.hSet(key, deviceId, secondsThreshold.toString());
|
||||
|
||||
this.notificationListeners.forEach((listener: Listener) => {
|
||||
const event: NotificationEvent = {
|
||||
event: 'addOrUpdate',
|
||||
notification
|
||||
};
|
||||
listener(event);
|
||||
});
|
||||
};
|
||||
|
||||
public deleteNotificationIfExists = async (lookupArguments: NotificationLookupArguments): Promise<void> => {
|
||||
const { shuttleId, stopId, deviceId } = lookupArguments;
|
||||
const key = this.getNotificationKey(shuttleId, stopId);
|
||||
|
||||
const secondsThreshold = await this.redisClient.hGet(key, deviceId);
|
||||
if (secondsThreshold) {
|
||||
await this.redisClient.hDel(key, deviceId);
|
||||
|
||||
// Check if hash is empty and delete it if so
|
||||
const remainingFields = await this.redisClient.hLen(key);
|
||||
if (remainingFields === 0) {
|
||||
await this.redisClient.del(key);
|
||||
}
|
||||
|
||||
this.notificationListeners.forEach((listener) => {
|
||||
const event: NotificationEvent = {
|
||||
event: 'delete',
|
||||
notification: {
|
||||
deviceId,
|
||||
shuttleId,
|
||||
stopId,
|
||||
secondsThreshold: parseInt(secondsThreshold)
|
||||
}
|
||||
};
|
||||
listener(event);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
public getAllNotificationsForShuttleAndStopId = async (
|
||||
shuttleId: string,
|
||||
stopId: string
|
||||
): Promise<ScheduledNotification[]> => {
|
||||
const key = this.getNotificationKey(shuttleId, stopId);
|
||||
const allNotifications = await this.redisClient.hGetAll(key);
|
||||
|
||||
return Object.entries(allNotifications).map(([deviceId, secondsThreshold]) => ({
|
||||
shuttleId,
|
||||
stopId,
|
||||
deviceId,
|
||||
secondsThreshold: parseInt(secondsThreshold)
|
||||
}));
|
||||
};
|
||||
|
||||
public getSecondsThresholdForNotificationIfExists = async (
|
||||
lookupArguments: NotificationLookupArguments
|
||||
): Promise<number | null> => {
|
||||
const { shuttleId, stopId, deviceId } = lookupArguments;
|
||||
const key = this.getNotificationKey(shuttleId, stopId);
|
||||
|
||||
const threshold = await this.redisClient.hGet(key, deviceId);
|
||||
return threshold ? parseInt(threshold) : null;
|
||||
};
|
||||
|
||||
public isNotificationScheduled = async (
|
||||
lookupArguments: NotificationLookupArguments
|
||||
): Promise<boolean> => {
|
||||
const threshold = await this.getSecondsThresholdForNotificationIfExists(lookupArguments);
|
||||
return threshold !== null;
|
||||
};
|
||||
|
||||
public subscribeToNotificationChanges = (listener: Listener): void => {
|
||||
const index = this.notificationListeners.findIndex(
|
||||
(existingListener) => existingListener === listener
|
||||
);
|
||||
if (index < 0) {
|
||||
this.notificationListeners.push(listener);
|
||||
}
|
||||
};
|
||||
|
||||
public unsubscribeFromNotificationChanges = (listener: Listener): void => {
|
||||
const index = this.notificationListeners.findIndex(
|
||||
(existingListener) => existingListener === listener
|
||||
);
|
||||
if (index >= 0) {
|
||||
this.notificationListeners.splice(index, 1);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
import { createClient, RedisClientType } from "redis";
|
||||
import { InMemoryNotificationRepository } from "../InMemoryNotificationRepository";
|
||||
import { NotificationEvent, NotificationRepository } from "../NotificationRepository";
|
||||
import { RedisNotificationRepository } from "../RedisNotificationRepository";
|
||||
|
||||
interface RepositoryHolder {
|
||||
name: string;
|
||||
factory(): Promise<NotificationRepository>,
|
||||
teardown(): Promise<void>,
|
||||
}
|
||||
|
||||
class InMemoryRepositoryHolder implements RepositoryHolder {
|
||||
name = 'InMemoryNotificationRepository';
|
||||
factory = async () => {
|
||||
return new InMemoryNotificationRepository();
|
||||
}
|
||||
teardown = async () => {}
|
||||
}
|
||||
|
||||
class RedisNotificationRepositoryHolder implements RepositoryHolder {
|
||||
repo: RedisNotificationRepository | undefined;
|
||||
redisClient: RedisClientType | undefined;
|
||||
|
||||
name = 'RedisNotificationRepository';
|
||||
factory = async () => {
|
||||
this.redisClient = createClient({
|
||||
url: process.env.REDIS_URL,
|
||||
});
|
||||
await this.redisClient.connect();
|
||||
this.repo = new RedisNotificationRepository(this.redisClient);
|
||||
return this.repo;
|
||||
}
|
||||
teardown = async () => {
|
||||
if (this.redisClient) {
|
||||
await this.redisClient.flushAll();
|
||||
await this.redisClient.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const repositoryImplementations = [
|
||||
new InMemoryRepositoryHolder(),
|
||||
new RedisNotificationRepositoryHolder(),
|
||||
]
|
||||
|
||||
describe.each(repositoryImplementations)('$name', (holder) => {
|
||||
let repo: NotificationRepository;
|
||||
|
||||
beforeEach(async () => {
|
||||
repo = await holder.factory();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await holder.teardown();
|
||||
})
|
||||
|
||||
const notification = {
|
||||
deviceId: "device1",
|
||||
shuttleId: "shuttle1",
|
||||
stopId: "stop1",
|
||||
secondsThreshold: 180
|
||||
};
|
||||
|
||||
describe("getAllNotificationsForShuttleAndStopId", () => {
|
||||
it("gets notifications correctly", async () => {
|
||||
await repo.addOrUpdateNotification(notification);
|
||||
|
||||
const result = await repo.getAllNotificationsForShuttleAndStopId("shuttle1", "stop1");
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toEqual(notification);
|
||||
});
|
||||
|
||||
it("returns empty array if no notifications", async () => {
|
||||
const result = await repo.getAllNotificationsForShuttleAndStopId("shuttle1", "stop1");
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getSecondsThresholdForNotificationIfExists", () => {
|
||||
it("gets the seconds threshold if exists", async () => {
|
||||
await repo.addOrUpdateNotification(notification);
|
||||
|
||||
const result = await repo.getSecondsThresholdForNotificationIfExists({
|
||||
deviceId: "device1",
|
||||
shuttleId: "shuttle1",
|
||||
stopId: "stop1"
|
||||
});
|
||||
expect(result).toBe(180);
|
||||
});
|
||||
|
||||
it("returns null if there is no seconds threshold", async () => {
|
||||
const result = await repo.getSecondsThresholdForNotificationIfExists({
|
||||
deviceId: "device1",
|
||||
shuttleId: "shuttle1",
|
||||
stopId: "stop1"
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("addOrUpdateNotification", () => {
|
||||
// Add/get flow is covered in getAllNotificationsForShuttleAndStopId
|
||||
|
||||
it("updates the seconds threshold if the notification exists already", async () => {
|
||||
await repo.addOrUpdateNotification(notification);
|
||||
await repo.addOrUpdateNotification({...notification, secondsThreshold: 300});
|
||||
|
||||
const result = await repo.getSecondsThresholdForNotificationIfExists({
|
||||
deviceId: "device1",
|
||||
shuttleId: "shuttle1",
|
||||
stopId: "stop1"
|
||||
});
|
||||
expect(result).toBe(300);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteNotificationIfExists", () => {
|
||||
it("deletes the notification", async () => {
|
||||
await repo.addOrUpdateNotification(notification);
|
||||
await repo.deleteNotificationIfExists(notification);
|
||||
|
||||
const result = await repo.getAllNotificationsForShuttleAndStopId("shuttle1", "stop1");
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
|
||||
it("does nothing if there's no notification", async () => {
|
||||
await expect(repo.deleteNotificationIfExists({
|
||||
deviceId: "device1",
|
||||
shuttleId: "shuttle1",
|
||||
stopId: "stop1"
|
||||
})).resolves.not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("subscribeToNotificationChanges", () => {
|
||||
it("calls subscribers when something is added", async () => {
|
||||
const mockCallback = jest.fn();
|
||||
repo.subscribeToNotificationChanges(mockCallback);
|
||||
|
||||
await repo.addOrUpdateNotification(notification);
|
||||
|
||||
const expectedEvent: NotificationEvent = {
|
||||
event: 'addOrUpdate',
|
||||
notification,
|
||||
}
|
||||
expect(mockCallback).toHaveBeenCalledTimes(1);
|
||||
expect(mockCallback).toHaveBeenCalledWith(expectedEvent);
|
||||
});
|
||||
|
||||
it("calls subscribers when something is updated", async () => {
|
||||
const mockCallback = jest.fn();
|
||||
repo.subscribeToNotificationChanges(mockCallback);
|
||||
|
||||
await repo.addOrUpdateNotification(notification);
|
||||
|
||||
const updatedNotification = {
|
||||
...notification,
|
||||
secondsThreshold: notification.secondsThreshold + 60,
|
||||
};
|
||||
|
||||
await repo.addOrUpdateNotification(updatedNotification);
|
||||
|
||||
const expectedEvent: NotificationEvent = {
|
||||
event: 'addOrUpdate',
|
||||
notification,
|
||||
}
|
||||
expect(mockCallback).toHaveBeenCalledTimes(2);
|
||||
expect(mockCallback).toHaveBeenCalledWith(expectedEvent);
|
||||
});
|
||||
|
||||
it("calls subscribers when something is deleted", async () => {
|
||||
await repo.addOrUpdateNotification(notification);
|
||||
|
||||
const mockCallback = jest.fn();
|
||||
repo.subscribeToNotificationChanges(mockCallback);
|
||||
|
||||
await repo.deleteNotificationIfExists(notification);
|
||||
|
||||
expect(mockCallback).toHaveBeenCalledTimes(1);
|
||||
|
||||
const expectedEvent: NotificationEvent = {
|
||||
event: 'delete',
|
||||
notification,
|
||||
};
|
||||
expect(mockCallback).toHaveBeenCalledWith(expectedEvent);
|
||||
});
|
||||
});
|
||||
|
||||
describe("unsubscribeFromNotificationChanges", () => {
|
||||
it("stops calling subscribers when unsubscribed", async () => {
|
||||
const mockCallback = jest.fn();
|
||||
repo.subscribeToNotificationChanges(mockCallback);
|
||||
|
||||
await repo.addOrUpdateNotification(notification);
|
||||
|
||||
repo.unsubscribeFromNotificationChanges(mockCallback);
|
||||
|
||||
await repo.deleteNotificationIfExists(notification);
|
||||
|
||||
expect(mockCallback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isNotificationScheduled", () => {
|
||||
it("returns true if the notification is in the repo", async () => {
|
||||
await repo.addOrUpdateNotification(notification);
|
||||
const result = await repo.isNotificationScheduled(notification);
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false if the notification isn't in the repo", async () => {
|
||||
const result = await repo.isNotificationScheduled(notification);
|
||||
expect(result).toBe(false);
|
||||
})
|
||||
});
|
||||
});
|
||||
161
src/repositories/parking/InMemoryParkingRepository.ts
Normal file
161
src/repositories/parking/InMemoryParkingRepository.ts
Normal file
@@ -0,0 +1,161 @@
|
||||
import { ParkingGetterSetterRepository } from "./ParkingGetterSetterRepository";
|
||||
import {
|
||||
IParkingStructure,
|
||||
IParkingStructureTimestampRecord
|
||||
} from "../../entities/ParkingRepositoryEntities";
|
||||
import { HistoricalParkingAverageQueryResult, HistoricalParkingAverageFilterArguments } from "./ParkingGetterRepository";
|
||||
import { CircularQueue } from "../../types/CircularQueue";
|
||||
import { PARKING_LOGGING_INTERVAL_MS } from "../../environment";
|
||||
|
||||
// If every 10 minutes, two weeks of data (6x per hour * 24x per day * 7x per week * 2)
|
||||
export const MAX_NUM_ENTRIES = 2016;
|
||||
|
||||
export type ParkingStructureID = string;
|
||||
|
||||
export class InMemoryParkingRepository implements ParkingGetterSetterRepository {
|
||||
private dataLastAdded: Map<ParkingStructureID, Date> = new Map();
|
||||
private loggingIntervalMs = PARKING_LOGGING_INTERVAL_MS;
|
||||
|
||||
constructor(
|
||||
private structures: Map<ParkingStructureID, IParkingStructure> = new Map(),
|
||||
private historicalData: Map<ParkingStructureID, CircularQueue<IParkingStructureTimestampRecord>> = new Map(),
|
||||
) {
|
||||
}
|
||||
|
||||
addOrUpdateParkingStructure = async (structure: IParkingStructure): Promise<void> => {
|
||||
this.structures.set(structure.id, { ...structure });
|
||||
await this.addHistoricalDataForStructure(structure);
|
||||
};
|
||||
|
||||
private addHistoricalDataForStructure = async (structure: IParkingStructure): Promise<void> => {
|
||||
const now = Date.now();
|
||||
const lastAdded = this.dataLastAdded.get(structure.id);
|
||||
|
||||
if (this.shouldLogHistoricalData(lastAdded, now)) {
|
||||
const timestampRecord = this.createTimestampRecord(structure, now);
|
||||
this.ensureHistoricalDataExists(structure.id);
|
||||
this.addRecordToHistoricalData(structure.id, timestampRecord);
|
||||
this.dataLastAdded.set(structure.id, new Date(now));
|
||||
}
|
||||
};
|
||||
|
||||
clearParkingStructureData = async (): Promise<void> => {
|
||||
this.structures.clear();
|
||||
this.historicalData.clear();
|
||||
this.dataLastAdded.clear();
|
||||
};
|
||||
|
||||
getParkingStructureById = async (id: string): Promise<IParkingStructure | null> => {
|
||||
const structure = this.structures.get(id);
|
||||
return structure ? { ...structure } : null;
|
||||
};
|
||||
|
||||
getParkingStructures = async (): Promise<IParkingStructure[]> => Array.from(this.structures.values()).map(structure => ({...structure}));
|
||||
|
||||
removeParkingStructureIfExists = async (id: string): Promise<IParkingStructure | null> => {
|
||||
const structure = this.structures.get(id);
|
||||
if (structure) {
|
||||
this.structures.delete(id);
|
||||
this.historicalData.delete(id);
|
||||
this.dataLastAdded.delete(id);
|
||||
return { ...structure };
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
getHistoricalAveragesOfParkingStructureCounts = async (id: string, options: HistoricalParkingAverageFilterArguments): Promise<HistoricalParkingAverageQueryResult[]> => {
|
||||
const queue = this.historicalData.get(id);
|
||||
if (!queue || queue.size() === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const records = this.extractRecordsFromQueue(queue);
|
||||
return this.calculateAveragesFromRecords(records, options);
|
||||
};
|
||||
|
||||
private shouldLogHistoricalData = (lastAdded: Date | undefined, currentTime: number): boolean => {
|
||||
return !lastAdded || (currentTime - lastAdded.getTime()) >= this.loggingIntervalMs;
|
||||
};
|
||||
|
||||
private createTimestampRecord = (structure: IParkingStructure, timestampMs: number): IParkingStructureTimestampRecord => ({
|
||||
id: structure.id,
|
||||
spotsAvailable: structure.spotsAvailable,
|
||||
timestampMs: new Date(timestampMs),
|
||||
});
|
||||
|
||||
private ensureHistoricalDataExists = (structureId: string): void => {
|
||||
if (!this.historicalData.has(structureId)) {
|
||||
this.historicalData.set(structureId, new CircularQueue<IParkingStructureTimestampRecord>(MAX_NUM_ENTRIES));
|
||||
}
|
||||
};
|
||||
|
||||
private addRecordToHistoricalData = (structureId: string, record: IParkingStructureTimestampRecord): void => {
|
||||
const sortingCallback = (a: IParkingStructureTimestampRecord, b: IParkingStructureTimestampRecord) => a.timestampMs.getTime() - b.timestampMs.getTime();
|
||||
this.historicalData.get(structureId)?.appendWithSorting(record, sortingCallback);
|
||||
};
|
||||
|
||||
private extractRecordsFromQueue = (queue: CircularQueue<IParkingStructureTimestampRecord>): IParkingStructureTimestampRecord[] => {
|
||||
const records: IParkingStructureTimestampRecord[] = [];
|
||||
for (let i = 0; i < queue.size(); i++) {
|
||||
const record = queue.get(i);
|
||||
if (record) {
|
||||
records.push(record);
|
||||
}
|
||||
}
|
||||
return records;
|
||||
};
|
||||
|
||||
private calculateAveragesFromRecords = (
|
||||
records: IParkingStructureTimestampRecord[],
|
||||
options: HistoricalParkingAverageFilterArguments
|
||||
): HistoricalParkingAverageQueryResult[] => {
|
||||
const results: HistoricalParkingAverageQueryResult[] = [];
|
||||
const { from, to, intervalMs } = options;
|
||||
|
||||
let currentIntervalStart = from.getTime();
|
||||
const endTime = to.getTime();
|
||||
|
||||
while (currentIntervalStart < endTime) {
|
||||
const currentIntervalEnd = Math.min(currentIntervalStart + intervalMs, endTime);
|
||||
const recordsInInterval = this.getRecordsInTimeRange(records, currentIntervalStart, currentIntervalEnd);
|
||||
|
||||
if (recordsInInterval.length > 0) {
|
||||
const averageResult = this.calculateAverageForInterval(currentIntervalStart, currentIntervalEnd, recordsInInterval);
|
||||
results.push(averageResult);
|
||||
}
|
||||
|
||||
currentIntervalStart = currentIntervalEnd;
|
||||
}
|
||||
|
||||
return results;
|
||||
};
|
||||
|
||||
private getRecordsInTimeRange = (
|
||||
records: IParkingStructureTimestampRecord[],
|
||||
startMs: number,
|
||||
endMs: number
|
||||
): IParkingStructureTimestampRecord[] => {
|
||||
return records.filter(record =>
|
||||
record.timestampMs.getTime() >= startMs && record.timestampMs.getTime() < endMs
|
||||
);
|
||||
};
|
||||
|
||||
private calculateAverageForInterval = (
|
||||
fromMs: number,
|
||||
toMs: number,
|
||||
records: IParkingStructureTimestampRecord[]
|
||||
): HistoricalParkingAverageQueryResult => {
|
||||
const totalSpotsAvailable = records.reduce((sum, record) => sum + record.spotsAvailable, 0);
|
||||
const averageSpotsAvailable = totalSpotsAvailable / records.length;
|
||||
|
||||
return {
|
||||
from: new Date(fromMs),
|
||||
to: new Date(toMs),
|
||||
averageSpotsAvailable
|
||||
};
|
||||
};
|
||||
|
||||
setLoggingInterval = (intervalMs: number): void => {
|
||||
this.loggingIntervalMs = intervalMs;
|
||||
};
|
||||
}
|
||||
26
src/repositories/parking/ParkingGetterRepository.ts
Normal file
26
src/repositories/parking/ParkingGetterRepository.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { IParkingStructure } from "../../entities/ParkingRepositoryEntities";
|
||||
|
||||
export interface HistoricalParkingAverageFilterArguments {
|
||||
from: Date;
|
||||
to: Date;
|
||||
intervalMs: number;
|
||||
}
|
||||
|
||||
export interface HistoricalParkingAverageQueryResult {
|
||||
from: Date;
|
||||
to: Date;
|
||||
averageSpotsAvailable: number;
|
||||
}
|
||||
|
||||
|
||||
export interface ParkingGetterRepository {
|
||||
getParkingStructures(): Promise<IParkingStructure[]>;
|
||||
getParkingStructureById(id: string): Promise<IParkingStructure | null>;
|
||||
|
||||
/**
|
||||
* Get historical averages of parking structure data using the filtering options.
|
||||
* @param id
|
||||
* @param options
|
||||
*/
|
||||
getHistoricalAveragesOfParkingStructureCounts(id: string, options: HistoricalParkingAverageFilterArguments): Promise<HistoricalParkingAverageQueryResult[]>;
|
||||
}
|
||||
12
src/repositories/parking/ParkingGetterSetterRepository.ts
Normal file
12
src/repositories/parking/ParkingGetterSetterRepository.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { IParkingStructure } from "../../entities/ParkingRepositoryEntities";
|
||||
import { ParkingGetterRepository } from "./ParkingGetterRepository";
|
||||
|
||||
export interface ParkingGetterSetterRepository extends ParkingGetterRepository {
|
||||
addOrUpdateParkingStructure(structure: IParkingStructure): Promise<void>;
|
||||
|
||||
removeParkingStructureIfExists(id: string): Promise<IParkingStructure | null>;
|
||||
|
||||
clearParkingStructureData(): Promise<void>;
|
||||
|
||||
setLoggingInterval(intervalMs: number): void;
|
||||
}
|
||||
204
src/repositories/parking/RedisParkingRepository.ts
Normal file
204
src/repositories/parking/RedisParkingRepository.ts
Normal file
@@ -0,0 +1,204 @@
|
||||
import { ParkingGetterSetterRepository } from "./ParkingGetterSetterRepository";
|
||||
import { IParkingStructure } from "../../entities/ParkingRepositoryEntities";
|
||||
import { HistoricalParkingAverageQueryResult, HistoricalParkingAverageFilterArguments } from "./ParkingGetterRepository";
|
||||
import { BaseRedisRepository } from "../BaseRedisRepository";
|
||||
import { PARKING_LOGGING_INTERVAL_MS } from "../../environment";
|
||||
|
||||
export type ParkingStructureID = string;
|
||||
|
||||
export class RedisParkingRepository extends BaseRedisRepository implements ParkingGetterSetterRepository {
|
||||
private dataLastAdded: Map<ParkingStructureID, Date> = new Map();
|
||||
private loggingIntervalMs = PARKING_LOGGING_INTERVAL_MS;
|
||||
|
||||
addOrUpdateParkingStructure = async (structure: IParkingStructure): Promise<void> => {
|
||||
const keys = this.createRedisKeys(structure.id);
|
||||
await this.redisClient.hSet(keys.structure, this.createRedisHashFromStructure(structure));
|
||||
await this.addHistoricalDataForStructure(structure);
|
||||
};
|
||||
|
||||
private addHistoricalDataForStructure = async (structure: IParkingStructure): Promise<void> => {
|
||||
const now = Date.now();
|
||||
const lastAdded = this.dataLastAdded.get(structure.id);
|
||||
|
||||
if (this.shouldLogHistoricalData(lastAdded, now)) {
|
||||
const keys = this.createRedisKeys(structure.id);
|
||||
await this.addTimeSeriesDataPoint(keys.timeSeries, now, structure.spotsAvailable, structure.id);
|
||||
this.dataLastAdded.set(structure.id, new Date(now));
|
||||
}
|
||||
};
|
||||
|
||||
clearParkingStructureData = async (): Promise<void> => {
|
||||
const structureKeys = await this.redisClient.keys('parking:structure:*');
|
||||
const timeSeriesKeys = await this.redisClient.keys('parking:timeseries:*');
|
||||
|
||||
const allKeys = [...structureKeys, ...timeSeriesKeys];
|
||||
if (allKeys.length > 0) {
|
||||
await this.redisClient.del(allKeys);
|
||||
}
|
||||
|
||||
this.dataLastAdded.clear();
|
||||
};
|
||||
|
||||
getParkingStructureById = async (id: string): Promise<IParkingStructure | null> => {
|
||||
const keys = this.createRedisKeys(id);
|
||||
const data = await this.redisClient.hGetAll(keys.structure);
|
||||
|
||||
if (Object.keys(data).length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.createStructureFromRedisData(data);
|
||||
};
|
||||
|
||||
getParkingStructures = async (): Promise<IParkingStructure[]> => {
|
||||
const keys = await this.redisClient.keys('parking:structure:*');
|
||||
const structures: IParkingStructure[] = [];
|
||||
|
||||
for (const key of keys) {
|
||||
const data = await this.redisClient.hGetAll(key);
|
||||
if (Object.keys(data).length > 0) {
|
||||
structures.push(this.createStructureFromRedisData(data));
|
||||
}
|
||||
}
|
||||
|
||||
return structures;
|
||||
};
|
||||
|
||||
removeParkingStructureIfExists = async (id: string): Promise<IParkingStructure | null> => {
|
||||
const structure = await this.getParkingStructureById(id);
|
||||
if (structure) {
|
||||
const keys = this.createRedisKeys(id);
|
||||
await this.redisClient.del([keys.structure, keys.timeSeries]);
|
||||
this.dataLastAdded.delete(id);
|
||||
return structure;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
getHistoricalAveragesOfParkingStructureCounts = async (id: string, options: HistoricalParkingAverageFilterArguments): Promise<HistoricalParkingAverageQueryResult[]> => {
|
||||
return this.calculateAveragesFromRecords(id, options);
|
||||
};
|
||||
|
||||
private createRedisKeys = (structureId: string) => ({
|
||||
structure: `parking:structure:${structureId}`,
|
||||
timeSeries: `parking:timeseries:${structureId}`
|
||||
});
|
||||
|
||||
private createRedisHashFromStructure = (structure: IParkingStructure): Record<string, string> => ({
|
||||
id: structure.id,
|
||||
name: structure.name,
|
||||
address: structure.address,
|
||||
capacity: structure.capacity.toString(),
|
||||
spotsAvailable: structure.spotsAvailable.toString(),
|
||||
latitude: structure.coordinates.latitude.toString(),
|
||||
longitude: structure.coordinates.longitude.toString(),
|
||||
updatedTime: structure.updatedTime.toISOString()
|
||||
});
|
||||
|
||||
private createStructureFromRedisData = (data: Record<string, string>): IParkingStructure => ({
|
||||
id: data.id,
|
||||
name: data.name,
|
||||
address: data.address,
|
||||
capacity: parseInt(data.capacity),
|
||||
spotsAvailable: parseInt(data.spotsAvailable),
|
||||
coordinates: {
|
||||
latitude: parseFloat(data.latitude),
|
||||
longitude: parseFloat(data.longitude)
|
||||
},
|
||||
updatedTime: new Date(data.updatedTime)
|
||||
});
|
||||
|
||||
private shouldLogHistoricalData = (lastAdded: Date | undefined, currentTime: number): boolean => {
|
||||
return !lastAdded || (currentTime - lastAdded.getTime()) >= this.loggingIntervalMs;
|
||||
};
|
||||
|
||||
private addTimeSeriesDataPoint = async (timeSeriesKey: string, timestamp: number, value: number, structureId: string): Promise<void> => {
|
||||
try {
|
||||
await this.redisClient.sendCommand([
|
||||
'TS.ADD',
|
||||
timeSeriesKey,
|
||||
timestamp.toString(),
|
||||
value.toString(),
|
||||
'LABELS',
|
||||
'structureId',
|
||||
structureId
|
||||
]);
|
||||
} catch (error) {
|
||||
await this.createTimeSeriesAndAddDataPoint(timeSeriesKey, timestamp, value, structureId);
|
||||
}
|
||||
};
|
||||
|
||||
private createTimeSeriesAndAddDataPoint = async (timeSeriesKey: string, timestamp: number, value: number, structureId: string): Promise<void> => {
|
||||
try {
|
||||
await this.redisClient.sendCommand([
|
||||
'TS.CREATE',
|
||||
timeSeriesKey,
|
||||
'RETENTION',
|
||||
'2678400000', // one month
|
||||
'LABELS',
|
||||
'structureId',
|
||||
structureId
|
||||
]);
|
||||
await this.redisClient.sendCommand([
|
||||
'TS.ADD',
|
||||
timeSeriesKey,
|
||||
timestamp.toString(),
|
||||
value.toString()
|
||||
]);
|
||||
} catch (createError) {
|
||||
await this.redisClient.sendCommand([
|
||||
'TS.ADD',
|
||||
timeSeriesKey,
|
||||
timestamp.toString(),
|
||||
value.toString()
|
||||
]);
|
||||
}
|
||||
};
|
||||
|
||||
private calculateAveragesFromRecords = async (
|
||||
id: string,
|
||||
options: HistoricalParkingAverageFilterArguments
|
||||
): Promise<HistoricalParkingAverageQueryResult[]> => {
|
||||
const keys = this.createRedisKeys(id);
|
||||
const { from, to, intervalMs } = options;
|
||||
const results: HistoricalParkingAverageQueryResult[] = [];
|
||||
|
||||
let currentIntervalStart = from.getTime();
|
||||
const endTime = to.getTime();
|
||||
|
||||
while (currentIntervalStart < endTime) {
|
||||
const currentIntervalEnd = Math.min(currentIntervalStart + intervalMs, endTime);
|
||||
|
||||
try {
|
||||
const aggregationResult = await this.redisClient.sendCommand([
|
||||
'TS.RANGE',
|
||||
keys.timeSeries,
|
||||
currentIntervalStart.toString(),
|
||||
currentIntervalEnd.toString(),
|
||||
'AGGREGATION',
|
||||
'AVG',
|
||||
intervalMs.toString()
|
||||
]) as [string, string][];
|
||||
|
||||
if (aggregationResult && aggregationResult.length > 0) {
|
||||
const [, averageValue] = aggregationResult[0];
|
||||
results.push({
|
||||
from: new Date(currentIntervalStart),
|
||||
to: new Date(currentIntervalEnd),
|
||||
averageSpotsAvailable: parseFloat(averageValue)
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
// If Redis aggregation fails, skip this interval
|
||||
}
|
||||
|
||||
currentIntervalStart = currentIntervalEnd;
|
||||
}
|
||||
|
||||
return results;
|
||||
};
|
||||
|
||||
setLoggingInterval = (intervalMs: number): void => {
|
||||
this.loggingIntervalMs = intervalMs;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
import { createClient, RedisClientType } from "redis";
|
||||
import { InMemoryParkingRepository, } from "../InMemoryParkingRepository";
|
||||
import { IParkingStructure } from "../../../entities/ParkingRepositoryEntities";
|
||||
import { ParkingGetterSetterRepository } from "../ParkingGetterSetterRepository";
|
||||
import { RedisParkingRepository } from "../RedisParkingRepository";
|
||||
import { HistoricalParkingAverageFilterArguments } from "../ParkingGetterRepository";
|
||||
import { RepositoryHolder } from "../../../../testHelpers/RepositoryHolder";
|
||||
|
||||
class InMemoryParkingRepositoryHolder implements RepositoryHolder<ParkingGetterSetterRepository> {
|
||||
name = 'InMemoryParkingRepository';
|
||||
factory = async () => {
|
||||
return new InMemoryParkingRepository();
|
||||
};
|
||||
teardown = async () => {};
|
||||
}
|
||||
|
||||
class RedisParkingRepositoryHolder implements RepositoryHolder<ParkingGetterSetterRepository> {
|
||||
repo: RedisParkingRepository | undefined;
|
||||
redisClient: RedisClientType | undefined;
|
||||
|
||||
name = 'RedisParkingRepository';
|
||||
factory = async () => {
|
||||
this.redisClient = createClient({
|
||||
url: process.env.REDIS_URL,
|
||||
});
|
||||
await this.redisClient.connect();
|
||||
this.repo = new RedisParkingRepository(this.redisClient);
|
||||
return this.repo;
|
||||
};
|
||||
teardown = async () => {
|
||||
if (this.redisClient) {
|
||||
await this.redisClient.flushAll();
|
||||
await this.redisClient.disconnect();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const repositoryImplementations = [
|
||||
new InMemoryParkingRepositoryHolder(),
|
||||
new RedisParkingRepositoryHolder(),
|
||||
];
|
||||
|
||||
describe.each(repositoryImplementations)('$name', (holder) => {
|
||||
let repository: ParkingGetterSetterRepository;
|
||||
const testStructure: IParkingStructure = {
|
||||
coordinates: {
|
||||
latitude: 33.794795,
|
||||
longitude: -117.850807,
|
||||
},
|
||||
spotsAvailable: 0,
|
||||
id: "1",
|
||||
name: "Anderson Parking Structure",
|
||||
capacity: 100,
|
||||
address: "300 E Walnut Ave, Orange, CA 92867",
|
||||
updatedTime: new Date(),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
repository = await holder.factory();
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await holder.teardown();
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
describe("addOrUpdateParkingStructure", () => {
|
||||
it("should add a new parking structure", async () => {
|
||||
await repository.addOrUpdateParkingStructure(testStructure);
|
||||
const result = await repository.getParkingStructureById(testStructure.id);
|
||||
expect(result).toEqual(testStructure);
|
||||
});
|
||||
|
||||
it("should update existing parking structure", async () => {
|
||||
await repository.addOrUpdateParkingStructure(testStructure);
|
||||
const updatedStructure = { ...testStructure, name: "Updated Garage" };
|
||||
await repository.addOrUpdateParkingStructure(updatedStructure);
|
||||
const result = await repository.getParkingStructureById(testStructure.id);
|
||||
expect(result).toEqual(updatedStructure);
|
||||
});
|
||||
});
|
||||
|
||||
describe("removeParkingStructureIfExists", () => {
|
||||
it("should remove existing parking structure and return it", async () => {
|
||||
await repository.addOrUpdateParkingStructure(testStructure);
|
||||
const removed = await repository.removeParkingStructureIfExists(testStructure.id);
|
||||
expect(removed).toEqual(testStructure);
|
||||
const result = await repository.getParkingStructureById(testStructure.id);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should return null when removing non-existent structure", async () => {
|
||||
const result = await repository.removeParkingStructureIfExists("non-existent");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("clearParkingStructureData", () => {
|
||||
it("should remove all parking structures", async () => {
|
||||
const structures = [
|
||||
testStructure,
|
||||
{ ...testStructure, id: "test-id-2", name: "Second Garage" }
|
||||
];
|
||||
|
||||
for (const structure of structures) {
|
||||
await repository.addOrUpdateParkingStructure(structure);
|
||||
}
|
||||
|
||||
await repository.clearParkingStructureData();
|
||||
const result = await repository.getParkingStructures();
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getParkingStructures", () => {
|
||||
it("should return empty array when no structures exist", async () => {
|
||||
const result = await repository.getParkingStructures();
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should return all added structures", async () => {
|
||||
const structures = [
|
||||
testStructure,
|
||||
{ ...testStructure, id: "test-id-2", name: "Second Garage" }
|
||||
];
|
||||
|
||||
for (const structure of structures) {
|
||||
await repository.addOrUpdateParkingStructure(structure);
|
||||
}
|
||||
|
||||
const result = await repository.getParkingStructures();
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result).toEqual(expect.arrayContaining(structures));
|
||||
});
|
||||
});
|
||||
|
||||
describe("getParkingStructureById", () => {
|
||||
it("should return null for non-existent structure", async () => {
|
||||
const result = await repository.getParkingStructureById("non-existent");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("should return structure by id", async () => {
|
||||
await repository.addOrUpdateParkingStructure(testStructure);
|
||||
const result = await repository.getParkingStructureById(testStructure.id);
|
||||
expect(result).toEqual(testStructure);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getHistoricalAveragesOfParkingStructureCounts", () => {
|
||||
it("should return empty array for non-existent structure or no data", async () => {
|
||||
const options: HistoricalParkingAverageFilterArguments = {
|
||||
from: new Date(1000),
|
||||
to: new Date(2000),
|
||||
intervalMs: 500
|
||||
};
|
||||
|
||||
expect(await repository.getHistoricalAveragesOfParkingStructureCounts("non-existent", options)).toEqual([]);
|
||||
|
||||
await repository.addOrUpdateParkingStructure(testStructure);
|
||||
expect(await repository.getHistoricalAveragesOfParkingStructureCounts(testStructure.id, options)).toEqual([]);
|
||||
});
|
||||
|
||||
it("should calculate average for one single large interval", async () => {
|
||||
// Set logging interval to 0 so every update creates historical data
|
||||
repository.setLoggingInterval(0);
|
||||
|
||||
await repository.addOrUpdateParkingStructure(testStructure);
|
||||
|
||||
const updates = [
|
||||
{ ...testStructure, spotsAvailable: 80, updatedTime: new Date() },
|
||||
{ ...testStructure, spotsAvailable: 70, updatedTime: new Date() },
|
||||
{ ...testStructure, spotsAvailable: 60, updatedTime: new Date() },
|
||||
];
|
||||
|
||||
for (let i = 0; i < updates.length; i++) {
|
||||
// Ensure that different timestamps are created, even after adding the first test structure
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
await repository.addOrUpdateParkingStructure(updates[i]);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const options: HistoricalParkingAverageFilterArguments = {
|
||||
from: new Date(now - 10000), // Look back 10 seconds
|
||||
to: new Date(now + 10000), // Look forward 10 seconds
|
||||
intervalMs: 20000 // Single large interval
|
||||
};
|
||||
|
||||
const result = await repository.getHistoricalAveragesOfParkingStructureCounts(testStructure.id, options);
|
||||
|
||||
// Should have at least some historical data
|
||||
expect(result.length).toEqual(1);
|
||||
if (result.length > 0) {
|
||||
expect(result[0]).toHaveProperty('from');
|
||||
expect(result[0]).toHaveProperty('to');
|
||||
expect(result[0].from).toBeInstanceOf(Date);
|
||||
expect(result[0].to).toBeInstanceOf(Date);
|
||||
expect(result[0]).toHaveProperty('averageSpotsAvailable');
|
||||
expect(result[0].averageSpotsAvailable).toBeCloseTo(52.5);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
629
src/repositories/shuttle/RedisShuttleRepository.ts
Normal file
629
src/repositories/shuttle/RedisShuttleRepository.ts
Normal file
@@ -0,0 +1,629 @@
|
||||
import { ShuttleGetterSetterRepository } from "./ShuttleGetterSetterRepository";
|
||||
import { IEta, IOrderedStop, IRoute, IShuttle, IStop, shuttleHasArrivedAtStop } from "../../entities/ShuttleRepositoryEntities";
|
||||
import {
|
||||
ShuttleRepositoryEvent,
|
||||
ShuttleRepositoryEventListener,
|
||||
ShuttleRepositoryEventName,
|
||||
ShuttleRepositoryEventPayloads,
|
||||
ShuttleStopArrival,
|
||||
ShuttleTravelTimeDataIdentifier,
|
||||
ShuttleTravelTimeDateFilterArguments
|
||||
} from "./ShuttleGetterRepository";
|
||||
import { BaseRedisRepository } from "../BaseRedisRepository";
|
||||
import { RedisClientType } from "redis";
|
||||
import createRedisClientForRepository from "../../helpers/createRedisClientForRepository";
|
||||
|
||||
export class RedisShuttleRepository extends BaseRedisRepository implements ShuttleGetterSetterRepository {
|
||||
constructor(
|
||||
redisClient: RedisClientType = createRedisClientForRepository(),
|
||||
readonly shuttleStopArrivalDegreeDelta: number = 0.001,
|
||||
) {
|
||||
super(redisClient);
|
||||
}
|
||||
|
||||
get isReady() {
|
||||
return this.redisClient.isReady;
|
||||
}
|
||||
|
||||
public async connect() {
|
||||
await this.redisClient.connect();
|
||||
}
|
||||
|
||||
public async disconnect() {
|
||||
await this.redisClient.disconnect();
|
||||
}
|
||||
|
||||
// EventEmitter override methods for type safety
|
||||
public override on<T extends ShuttleRepositoryEventName>(
|
||||
event: T,
|
||||
listener: ShuttleRepositoryEventListener<T>,
|
||||
): this;
|
||||
public override on(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.on(event, listener);
|
||||
}
|
||||
|
||||
public override once<T extends ShuttleRepositoryEventName>(
|
||||
event: T,
|
||||
listener: ShuttleRepositoryEventListener<T>,
|
||||
): this;
|
||||
public override once(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.once(event, listener);
|
||||
}
|
||||
|
||||
public override off<T extends ShuttleRepositoryEventName>(
|
||||
event: T,
|
||||
listener: ShuttleRepositoryEventListener<T>,
|
||||
): this;
|
||||
public override off(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.off(event, listener);
|
||||
}
|
||||
|
||||
public override addListener<T extends ShuttleRepositoryEventName>(
|
||||
event: T,
|
||||
listener: ShuttleRepositoryEventListener<T>,
|
||||
): this;
|
||||
public override addListener(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.addListener(event, listener);
|
||||
}
|
||||
|
||||
public override removeListener<T extends ShuttleRepositoryEventName>(
|
||||
event: T,
|
||||
listener: ShuttleRepositoryEventListener<T>,
|
||||
): this;
|
||||
public override removeListener(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.removeListener(event, listener);
|
||||
}
|
||||
|
||||
public override emit<T extends ShuttleRepositoryEventName>(
|
||||
event: T,
|
||||
payload: ShuttleRepositoryEventPayloads[T],
|
||||
): boolean;
|
||||
public override emit(event: string | symbol, ...args: any[]): boolean {
|
||||
return super.emit(event, ...args);
|
||||
}
|
||||
|
||||
// Key prefixes for individual entity keys
|
||||
private readonly stopKeyPrefix = 'shuttle:stop:';
|
||||
private readonly routeKeyPrefix = 'shuttle:route:';
|
||||
private readonly shuttleKeyPrefix = 'shuttle:shuttle:';
|
||||
private readonly orderedStopKeyPrefix = 'shuttle:orderedstop:';
|
||||
private readonly lastStopKeyPrefix = 'shuttle:laststop:';
|
||||
private readonly historicalEtaKeyPrefix = 'shuttle:eta:historical:';
|
||||
|
||||
// Key patterns for bulk operations (e.g., getting all keys, clearing data)
|
||||
private readonly stopKeyPattern = 'shuttle:stop:*';
|
||||
private readonly routeKeyPattern = 'shuttle:route:*';
|
||||
private readonly shuttleKeyPattern = 'shuttle:shuttle:*';
|
||||
private readonly orderedStopKeyPattern = 'shuttle:orderedstop:*';
|
||||
private readonly lastStopKeyPattern = 'shuttle:laststop:*';
|
||||
|
||||
/**
|
||||
* Represents a set storing the shuttles that are currently at a stop.
|
||||
*/
|
||||
private readonly shuttleIsAtStopKey = 'shuttle:atstop';
|
||||
|
||||
// Helper methods for Redis key generation
|
||||
private readonly createStopKey = (stopId: string) => `${this.stopKeyPrefix}${stopId}`;
|
||||
private readonly createRouteKey = (routeId: string) => `${this.routeKeyPrefix}${routeId}`;
|
||||
private readonly createShuttleKey = (shuttleId: string) => `${this.shuttleKeyPrefix}${shuttleId}`;
|
||||
private readonly createOrderedStopKey = (routeId: string, stopId: string) => `${this.orderedStopKeyPrefix}${routeId}:${stopId}`;
|
||||
private readonly createShuttleLastStopKey = (shuttleId: string) => `${this.lastStopKeyPrefix}${shuttleId}`;
|
||||
private readonly createHistoricalEtaTimeSeriesKey = (routeId: string, fromStopId: string, toStopId: string) => {
|
||||
return `${this.historicalEtaKeyPrefix}${routeId}:${fromStopId}:${toStopId}`;
|
||||
};
|
||||
|
||||
// Helper methods for converting entities to Redis hashes
|
||||
private createRedisHashFromStop = (stop: IStop): Record<string, string> => ({
|
||||
id: stop.id,
|
||||
name: stop.name,
|
||||
systemId: stop.systemId,
|
||||
latitude: stop.coordinates.latitude.toString(),
|
||||
longitude: stop.coordinates.longitude.toString(),
|
||||
updatedTime: stop.updatedTime.toISOString(),
|
||||
});
|
||||
|
||||
private createStopFromRedisData = (data: Record<string, string>): IStop => ({
|
||||
id: data.id,
|
||||
name: data.name,
|
||||
systemId: data.systemId,
|
||||
coordinates: {
|
||||
latitude: parseFloat(data.latitude),
|
||||
longitude: parseFloat(data.longitude),
|
||||
},
|
||||
updatedTime: new Date(data.updatedTime),
|
||||
});
|
||||
|
||||
private createRedisHashFromRoute = (route: IRoute): Record<string, string> => ({
|
||||
id: route.id,
|
||||
name: route.name,
|
||||
color: route.color,
|
||||
systemId: route.systemId,
|
||||
polylineCoordinates: JSON.stringify(route.polylineCoordinates),
|
||||
updatedTime: route.updatedTime.toISOString(),
|
||||
});
|
||||
|
||||
private createRouteFromRedisData = (data: Record<string, string>): IRoute => ({
|
||||
id: data.id,
|
||||
name: data.name,
|
||||
color: data.color,
|
||||
systemId: data.systemId,
|
||||
polylineCoordinates: JSON.parse(data.polylineCoordinates),
|
||||
updatedTime: new Date(data.updatedTime),
|
||||
});
|
||||
|
||||
private createRedisHashFromShuttle = (shuttle: IShuttle): Record<string, string> => ({
|
||||
id: shuttle.id,
|
||||
name: shuttle.name,
|
||||
routeId: shuttle.routeId,
|
||||
systemId: shuttle.systemId,
|
||||
latitude: shuttle.coordinates.latitude.toString(),
|
||||
longitude: shuttle.coordinates.longitude.toString(),
|
||||
orientationInDegrees: shuttle.orientationInDegrees.toString(),
|
||||
updatedTime: shuttle.updatedTime.toISOString(),
|
||||
});
|
||||
|
||||
private createShuttleFromRedisData = (data: Record<string, string>): IShuttle => ({
|
||||
id: data.id,
|
||||
name: data.name,
|
||||
routeId: data.routeId,
|
||||
systemId: data.systemId,
|
||||
coordinates: {
|
||||
latitude: parseFloat(data.latitude),
|
||||
longitude: parseFloat(data.longitude),
|
||||
},
|
||||
orientationInDegrees: parseFloat(data.orientationInDegrees),
|
||||
updatedTime: new Date(data.updatedTime),
|
||||
});
|
||||
|
||||
private createEtaFromRedisData = (data: Record<string, string>): IEta => ({
|
||||
secondsRemaining: parseFloat(data.secondsRemaining),
|
||||
shuttleId: data.shuttleId,
|
||||
stopId: data.stopId,
|
||||
systemId: data.systemId,
|
||||
updatedTime: new Date(data.updatedTime),
|
||||
});
|
||||
|
||||
private createRedisHashFromOrderedStop = (orderedStop: IOrderedStop): Record<string, string> => {
|
||||
const hash: Record<string, string> = {
|
||||
routeId: orderedStop.routeId,
|
||||
stopId: orderedStop.stopId,
|
||||
position: orderedStop.position.toString(),
|
||||
systemId: orderedStop.systemId,
|
||||
updatedTime: orderedStop.updatedTime.toISOString(),
|
||||
};
|
||||
|
||||
if (orderedStop.nextStop) {
|
||||
hash.nextStopRouteId = orderedStop.nextStop.routeId;
|
||||
hash.nextStopStopId = orderedStop.nextStop.stopId;
|
||||
}
|
||||
|
||||
if (orderedStop.previousStop) {
|
||||
hash.previousStopRouteId = orderedStop.previousStop.routeId;
|
||||
hash.previousStopStopId = orderedStop.previousStop.stopId;
|
||||
}
|
||||
|
||||
return hash;
|
||||
};
|
||||
|
||||
private createOrderedStopFromRedisData = (data: Record<string, string>): IOrderedStop => {
|
||||
const orderedStop: IOrderedStop = {
|
||||
routeId: data.routeId,
|
||||
stopId: data.stopId,
|
||||
position: parseInt(data.position),
|
||||
systemId: data.systemId,
|
||||
updatedTime: new Date(data.updatedTime),
|
||||
};
|
||||
|
||||
// Note: We only store the IDs of next/previous stops, not full objects
|
||||
// to avoid circular references in Redis. These would need to be
|
||||
// resolved separately if needed.
|
||||
if (data.nextStopRouteId && data.nextStopStopId) {
|
||||
orderedStop.nextStop = {
|
||||
routeId: data.nextStopRouteId,
|
||||
stopId: data.nextStopStopId,
|
||||
position: 0, // placeholder
|
||||
systemId: data.systemId,
|
||||
updatedTime: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
if (data.previousStopRouteId && data.previousStopStopId) {
|
||||
orderedStop.previousStop = {
|
||||
routeId: data.previousStopRouteId,
|
||||
stopId: data.previousStopStopId,
|
||||
position: 0, // placeholder
|
||||
systemId: data.systemId,
|
||||
updatedTime: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
return orderedStop;
|
||||
};
|
||||
|
||||
// Getter methods
|
||||
public async getStops(): Promise<IStop[]> {
|
||||
const keys = await this.redisClient.keys(this.stopKeyPattern);
|
||||
const stops: IStop[] = [];
|
||||
|
||||
for (const key of keys) {
|
||||
const data = await this.redisClient.hGetAll(key);
|
||||
if (Object.keys(data).length > 0) {
|
||||
stops.push(this.createStopFromRedisData(data));
|
||||
}
|
||||
}
|
||||
|
||||
return stops;
|
||||
}
|
||||
|
||||
public async getStopById(stopId: string): Promise<IStop | null> {
|
||||
const key = this.createStopKey(stopId);
|
||||
const data = await this.redisClient.hGetAll(key);
|
||||
|
||||
if (Object.keys(data).length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.createStopFromRedisData(data);
|
||||
}
|
||||
|
||||
public async getRoutes(): Promise<IRoute[]> {
|
||||
const keys = await this.redisClient.keys(this.routeKeyPattern);
|
||||
const routes: IRoute[] = [];
|
||||
|
||||
for (const key of keys) {
|
||||
const data = await this.redisClient.hGetAll(key);
|
||||
if (Object.keys(data).length > 0) {
|
||||
routes.push(this.createRouteFromRedisData(data));
|
||||
}
|
||||
}
|
||||
|
||||
return routes;
|
||||
}
|
||||
|
||||
public async getRouteById(routeId: string): Promise<IRoute | null> {
|
||||
const key = this.createRouteKey(routeId);
|
||||
const data = await this.redisClient.hGetAll(key);
|
||||
|
||||
if (Object.keys(data).length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.createRouteFromRedisData(data);
|
||||
}
|
||||
|
||||
public async getShuttles(): Promise<IShuttle[]> {
|
||||
const keys = await this.redisClient.keys(this.shuttleKeyPattern);
|
||||
const shuttles: IShuttle[] = [];
|
||||
|
||||
for (const key of keys) {
|
||||
const data = await this.redisClient.hGetAll(key);
|
||||
if (Object.keys(data).length > 0) {
|
||||
shuttles.push(this.createShuttleFromRedisData(data));
|
||||
}
|
||||
}
|
||||
|
||||
return shuttles;
|
||||
}
|
||||
|
||||
public async getShuttlesByRouteId(routeId: string): Promise<IShuttle[]> {
|
||||
const allShuttles = await this.getShuttles();
|
||||
return allShuttles.filter(shuttle => shuttle.routeId === routeId);
|
||||
}
|
||||
|
||||
public async getShuttleById(shuttleId: string): Promise<IShuttle | null> {
|
||||
const key = this.createShuttleKey(shuttleId);
|
||||
const data = await this.redisClient.hGetAll(key);
|
||||
|
||||
if (Object.keys(data).length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.createShuttleFromRedisData(data);
|
||||
}
|
||||
|
||||
public async getOrderedStopByRouteAndStopId(routeId: string, stopId: string): Promise<IOrderedStop | null> {
|
||||
const key = this.createOrderedStopKey(routeId, stopId);
|
||||
const data = await this.redisClient.hGetAll(key);
|
||||
|
||||
if (Object.keys(data).length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.createOrderedStopFromRedisData(data);
|
||||
}
|
||||
|
||||
public async getOrderedStopsByStopId(stopId: string): Promise<IOrderedStop[]> {
|
||||
const keys = await this.redisClient.keys(this.orderedStopKeyPattern);
|
||||
const orderedStops: IOrderedStop[] = [];
|
||||
|
||||
for (const key of keys) {
|
||||
const data = await this.redisClient.hGetAll(key);
|
||||
if (Object.keys(data).length > 0 && data.stopId === stopId) {
|
||||
orderedStops.push(this.createOrderedStopFromRedisData(data));
|
||||
}
|
||||
}
|
||||
|
||||
return orderedStops;
|
||||
}
|
||||
|
||||
public async getOrderedStopsByRouteId(routeId: string): Promise<IOrderedStop[]> {
|
||||
const keys = await this.redisClient.keys(`${this.orderedStopKeyPrefix}${routeId}:*`);
|
||||
const orderedStops: IOrderedStop[] = [];
|
||||
|
||||
for (const key of keys) {
|
||||
const data = await this.redisClient.hGetAll(key);
|
||||
if (Object.keys(data).length > 0) {
|
||||
orderedStops.push(this.createOrderedStopFromRedisData(data));
|
||||
}
|
||||
}
|
||||
|
||||
return orderedStops;
|
||||
}
|
||||
|
||||
// Setter/update methods
|
||||
public async addOrUpdateRoute(route: IRoute): Promise<void> {
|
||||
const key = this.createRouteKey(route.id);
|
||||
await this.redisClient.hSet(key, this.createRedisHashFromRoute(route));
|
||||
}
|
||||
|
||||
public async addOrUpdateShuttle(
|
||||
shuttle: IShuttle,
|
||||
travelTimeTimestamp = Date.now(),
|
||||
): Promise<void> {
|
||||
const key = this.createShuttleKey(shuttle.id);
|
||||
await this.redisClient.hSet(key, this.createRedisHashFromShuttle(shuttle));
|
||||
|
||||
this.emit(ShuttleRepositoryEvent.SHUTTLE_UPDATED, shuttle);
|
||||
|
||||
await this.updateLastStopArrival(shuttle, travelTimeTimestamp);
|
||||
}
|
||||
|
||||
private async updateLastStopArrival(
|
||||
shuttle: IShuttle,
|
||||
travelTimeTimestamp = Date.now(),
|
||||
) {
|
||||
const isAtStop = await this.checkIfShuttleIsAtStop(shuttle.id);
|
||||
|
||||
let arrivedStop: IStop | undefined;
|
||||
|
||||
if (isAtStop) {
|
||||
// Allow retrieval of the shuttle's current stop
|
||||
// Will still return undefined when the shuttle leaves the stop
|
||||
arrivedStop = await this.getArrivedStopIfNextStop(shuttle, true);
|
||||
} else {
|
||||
arrivedStop = await this.getArrivedStopIfNextStop(shuttle, false);
|
||||
}
|
||||
|
||||
// Will not fire *any* events if the same stop
|
||||
const lastStop = await this.getShuttleLastStopArrival(shuttle.id);
|
||||
if (lastStop?.stopId === arrivedStop?.id) return;
|
||||
|
||||
if (isAtStop) {
|
||||
if (lastStop) {
|
||||
this.emit(ShuttleRepositoryEvent.SHUTTLE_WILL_LEAVE_STOP, {
|
||||
stopArrivalThatShuttleIsLeaving: lastStop,
|
||||
});
|
||||
}
|
||||
await this.markShuttleAsNotAtStop(shuttle.id);
|
||||
}
|
||||
|
||||
if (arrivedStop) {
|
||||
const shuttleArrival = {
|
||||
stopId: arrivedStop.id,
|
||||
timestamp: new Date(travelTimeTimestamp),
|
||||
shuttleId: shuttle.id,
|
||||
};
|
||||
this.emit(ShuttleRepositoryEvent.SHUTTLE_WILL_ARRIVE_AT_STOP, {
|
||||
lastStopArrival: lastStop,
|
||||
willArriveAt: shuttleArrival,
|
||||
});
|
||||
await this.markShuttleAsAtStop(shuttleArrival.shuttleId);
|
||||
await this.updateShuttleLastStopArrival(shuttleArrival);
|
||||
}
|
||||
}
|
||||
|
||||
private async markShuttleAsAtStop(shuttleId: string) {
|
||||
await this.redisClient.sAdd(this.shuttleIsAtStopKey, shuttleId);
|
||||
}
|
||||
|
||||
private async markShuttleAsNotAtStop(shuttleId: string) {
|
||||
await this.redisClient.sRem(this.shuttleIsAtStopKey, shuttleId);
|
||||
}
|
||||
|
||||
public async checkIfShuttleIsAtStop(shuttleId: string) {
|
||||
return await this.redisClient.sIsMember(this.shuttleIsAtStopKey, shuttleId);
|
||||
}
|
||||
|
||||
public async getAverageTravelTimeSeconds(
|
||||
{ routeId, fromStopId, toStopId }: ShuttleTravelTimeDataIdentifier,
|
||||
{ from, to }: ShuttleTravelTimeDateFilterArguments,
|
||||
): Promise<number | undefined> {
|
||||
const timeSeriesKey = this.createHistoricalEtaTimeSeriesKey(routeId, fromStopId, toStopId);
|
||||
const fromTimestamp = from.getTime();
|
||||
const toTimestamp = to.getTime();
|
||||
const intervalMs = toTimestamp - fromTimestamp + 1;
|
||||
|
||||
try {
|
||||
const aggregationResult = await this.redisClient.sendCommand([
|
||||
'TS.RANGE',
|
||||
timeSeriesKey,
|
||||
fromTimestamp.toString(),
|
||||
toTimestamp.toString(),
|
||||
'AGGREGATION',
|
||||
'AVG',
|
||||
intervalMs.toString()
|
||||
]) as [string, string][];
|
||||
|
||||
if (aggregationResult && aggregationResult.length > 0) {
|
||||
const [, averageValue] = aggregationResult[0];
|
||||
return parseFloat(averageValue);
|
||||
}
|
||||
|
||||
return;
|
||||
} catch (error) {
|
||||
console.warn(`Failed to get average travel time: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
public async getArrivedStopIfNextStop(
|
||||
shuttle: IShuttle,
|
||||
canReturnShuttleCurrentStop: boolean = false,
|
||||
): Promise<IStop | undefined> {
|
||||
const degreeDelta = this.shuttleStopArrivalDegreeDelta;
|
||||
|
||||
const lastStopArrival = await this.getShuttleLastStopArrival(shuttle.id);
|
||||
if (lastStopArrival) {
|
||||
// Return the shuttle's current stop depending on the flag
|
||||
if (canReturnShuttleCurrentStop) {
|
||||
const lastStop = await this.getStopById(lastStopArrival.stopId);
|
||||
if (lastStop && shuttleHasArrivedAtStop(shuttle, lastStop, degreeDelta)) {
|
||||
return lastStop;
|
||||
}
|
||||
}
|
||||
|
||||
const lastOrderedStop = await this.getOrderedStopByRouteAndStopId(shuttle.routeId, lastStopArrival.stopId);
|
||||
const orderedStopAfter = lastOrderedStop?.nextStop;
|
||||
if (orderedStopAfter) {
|
||||
const stopAfter = await this.getStopById(orderedStopAfter.stopId);
|
||||
if (stopAfter && shuttleHasArrivedAtStop(shuttle, stopAfter, degreeDelta)) {
|
||||
return stopAfter;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const orderedStops = await this.getOrderedStopsByRouteId(shuttle.routeId);
|
||||
|
||||
for (const orderedStop of orderedStops) {
|
||||
const stop = await this.getStopById(orderedStop.stopId);
|
||||
if (stop != null && shuttleHasArrivedAtStop(shuttle, stop, degreeDelta)) {
|
||||
return stop;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
public async getShuttleLastStopArrival(shuttleId: string): Promise<ShuttleStopArrival | undefined> {
|
||||
const key = this.createShuttleLastStopKey(shuttleId);
|
||||
const data = await this.redisClient.hGetAll(key);
|
||||
|
||||
if (Object.keys(data).length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
shuttleId,
|
||||
stopId: data.stopId,
|
||||
timestamp: new Date(data.timestamp),
|
||||
};
|
||||
}
|
||||
|
||||
private async updateShuttleLastStopArrival(lastStopArrival: ShuttleStopArrival) {
|
||||
const key = this.createShuttleLastStopKey(lastStopArrival.shuttleId);
|
||||
await this.redisClient.hSet(key, {
|
||||
stopId: lastStopArrival.stopId,
|
||||
timestamp: lastStopArrival.timestamp.toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
public async addOrUpdateStop(stop: IStop): Promise<void> {
|
||||
const key = this.createStopKey(stop.id);
|
||||
await this.redisClient.hSet(key, this.createRedisHashFromStop(stop));
|
||||
}
|
||||
|
||||
public async addOrUpdateOrderedStop(orderedStop: IOrderedStop): Promise<void> {
|
||||
const key = this.createOrderedStopKey(orderedStop.routeId, orderedStop.stopId);
|
||||
await this.redisClient.hSet(key, this.createRedisHashFromOrderedStop(orderedStop));
|
||||
}
|
||||
|
||||
// Remove methods
|
||||
public async removeRouteIfExists(routeId: string): Promise<IRoute | null> {
|
||||
const route = await this.getRouteById(routeId);
|
||||
if (route) {
|
||||
const key = this.createRouteKey(routeId);
|
||||
await this.redisClient.del(key);
|
||||
return route;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public async removeShuttleIfExists(shuttleId: string): Promise<IShuttle | null> {
|
||||
const shuttle = await this.getShuttleById(shuttleId);
|
||||
if (shuttle) {
|
||||
const key = this.createShuttleKey(shuttleId);
|
||||
await this.redisClient.del(key);
|
||||
this.emit(ShuttleRepositoryEvent.SHUTTLE_REMOVED, shuttle);
|
||||
|
||||
await this.removeShuttleLastStopIfExists(shuttleId);
|
||||
await this.markShuttleAsNotAtStop(shuttleId);
|
||||
|
||||
return shuttle;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public async removeStopIfExists(stopId: string): Promise<IStop | null> {
|
||||
const stop = await this.getStopById(stopId);
|
||||
if (stop) {
|
||||
const key = this.createStopKey(stopId);
|
||||
await this.redisClient.del(key);
|
||||
return stop;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public async removeOrderedStopIfExists(stopId: string, routeId: string): Promise<IOrderedStop | null> {
|
||||
const orderedStop = await this.getOrderedStopByRouteAndStopId(routeId, stopId);
|
||||
if (orderedStop) {
|
||||
const key = this.createOrderedStopKey(routeId, stopId);
|
||||
await this.redisClient.del(key);
|
||||
return orderedStop;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async removeShuttleLastStopIfExists(shuttleId: string) {
|
||||
const lastStop = await this.getShuttleLastStopArrival(shuttleId);
|
||||
if (lastStop) {
|
||||
const key = this.createShuttleLastStopKey(shuttleId);
|
||||
await this.redisClient.del(key);
|
||||
return lastStop;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Clear methods
|
||||
private async clearRedisKeys(pattern: string): Promise<void> {
|
||||
const keys = await this.redisClient.keys(pattern);
|
||||
if (keys.length > 0) {
|
||||
await this.redisClient.del(keys);
|
||||
}
|
||||
}
|
||||
|
||||
public async clearShuttleData(): Promise<void> {
|
||||
await this.clearRedisKeys(this.shuttleKeyPattern);
|
||||
await this.clearShuttleLastStopData();
|
||||
await this.clearShuttleIsAtStopData();
|
||||
}
|
||||
|
||||
public async clearOrderedStopData(): Promise<void> {
|
||||
await this.clearRedisKeys(this.orderedStopKeyPattern);
|
||||
}
|
||||
|
||||
public async clearRouteData(): Promise<void> {
|
||||
await this.clearRedisKeys(this.routeKeyPattern);
|
||||
}
|
||||
|
||||
public async clearStopData(): Promise<void> {
|
||||
await this.clearRedisKeys(this.stopKeyPattern);
|
||||
}
|
||||
|
||||
private async clearShuttleLastStopData(): Promise<void> {
|
||||
await this.clearRedisKeys(this.lastStopKeyPattern);
|
||||
}
|
||||
|
||||
private async clearShuttleIsAtStopData(): Promise<void> {
|
||||
await this.clearRedisKeys(this.shuttleIsAtStopKey);
|
||||
}
|
||||
}
|
||||
119
src/repositories/shuttle/ShuttleGetterRepository.ts
Normal file
119
src/repositories/shuttle/ShuttleGetterRepository.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { IEta, IOrderedStop, IRoute, IShuttle, IStop } from "../../entities/ShuttleRepositoryEntities";
|
||||
import type EventEmitter from "node:events";
|
||||
|
||||
export const ShuttleRepositoryEvent = {
|
||||
SHUTTLE_UPDATED: "shuttleUpdated",
|
||||
SHUTTLE_REMOVED: "shuttleRemoved",
|
||||
SHUTTLE_WILL_ARRIVE_AT_STOP: "shuttleArrivedAtStop",
|
||||
SHUTTLE_WILL_LEAVE_STOP: "shuttleWillLeaveStop",
|
||||
} as const;
|
||||
|
||||
export type ShuttleRepositoryEventName = typeof ShuttleRepositoryEvent[keyof typeof ShuttleRepositoryEvent];
|
||||
|
||||
export type EtaRemovedEventPayload = IEta;
|
||||
export type EtaDataClearedEventPayload = IEta[];
|
||||
|
||||
export interface ShuttleWillArriveAtStopPayload {
|
||||
lastStopArrival?: ShuttleStopArrival;
|
||||
willArriveAt: ShuttleStopArrival;
|
||||
};
|
||||
|
||||
export type ShuttleIsNearStopPayload = ShuttleWillArriveAtStopPayload;
|
||||
|
||||
export interface ShuttleWillLeaveStopPayload {
|
||||
stopArrivalThatShuttleIsLeaving: ShuttleStopArrival;
|
||||
}
|
||||
|
||||
export interface ShuttleRepositoryEventPayloads {
|
||||
[ShuttleRepositoryEvent.SHUTTLE_UPDATED]: IShuttle,
|
||||
[ShuttleRepositoryEvent.SHUTTLE_REMOVED]: IShuttle,
|
||||
[ShuttleRepositoryEvent.SHUTTLE_WILL_ARRIVE_AT_STOP]: ShuttleWillArriveAtStopPayload,
|
||||
[ShuttleRepositoryEvent.SHUTTLE_WILL_LEAVE_STOP]: ShuttleWillLeaveStopPayload,
|
||||
}
|
||||
|
||||
export type ShuttleRepositoryEventListener<T extends ShuttleRepositoryEventName> = (
|
||||
payload: ShuttleRepositoryEventPayloads[T],
|
||||
) => void;
|
||||
|
||||
export interface ShuttleStopArrival {
|
||||
shuttleId: string;
|
||||
stopId: string;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
export interface ShuttleTravelTimeDataIdentifier {
|
||||
routeId: string;
|
||||
fromStopId: string;
|
||||
toStopId: string;
|
||||
}
|
||||
|
||||
export interface ShuttleTravelTimeDateFilterArguments {
|
||||
from: Date;
|
||||
to: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shuttle getter repository to be linked to a system.
|
||||
*/
|
||||
export interface ShuttleGetterRepository extends EventEmitter {
|
||||
getStops(): Promise<IStop[]>;
|
||||
getStopById(stopId: string): Promise<IStop | null>;
|
||||
|
||||
getRoutes(): Promise<IRoute[]>;
|
||||
getRouteById(routeId: string): Promise<IRoute | null>;
|
||||
|
||||
getShuttles(): Promise<IShuttle[]>;
|
||||
getShuttleById(shuttleId: string): Promise<IShuttle | null>;
|
||||
getShuttlesByRouteId(routeId: string): Promise<IShuttle[]>;
|
||||
|
||||
on<T extends ShuttleRepositoryEventName>(event: T, listener: ShuttleRepositoryEventListener<T>): this;
|
||||
once<T extends ShuttleRepositoryEventName>(event: T, listener: ShuttleRepositoryEventListener<T>): this;
|
||||
off<T extends ShuttleRepositoryEventName>(event: T, listener: ShuttleRepositoryEventListener<T>): this;
|
||||
addListener<T extends ShuttleRepositoryEventName>(event: T, listener: ShuttleRepositoryEventListener<T>): this;
|
||||
removeListener<T extends ShuttleRepositoryEventName>(event: T, listener: ShuttleRepositoryEventListener<T>): this;
|
||||
|
||||
getOrderedStopByRouteAndStopId(routeId: string, stopId: string): Promise<IOrderedStop | null>;
|
||||
|
||||
/**
|
||||
* Get ordered stops with the given stop ID.
|
||||
* Returns an empty array if no ordered stops found.
|
||||
* @param stopId
|
||||
*/
|
||||
getOrderedStopsByStopId(stopId: string): Promise<IOrderedStop[]>;
|
||||
|
||||
/**
|
||||
* Get ordered stops with the given route ID.
|
||||
* Returns an empty array if no ordered stops found.
|
||||
* @param routeId
|
||||
*/
|
||||
getOrderedStopsByRouteId(routeId: string): Promise<IOrderedStop[]>;
|
||||
|
||||
/**
|
||||
* Get the last stop arrival for a shuttle.
|
||||
* Returns undefined if no last stop arrival has been recorded.
|
||||
* @param shuttleId
|
||||
*/
|
||||
getShuttleLastStopArrival(shuttleId: string): Promise<ShuttleStopArrival | undefined>;
|
||||
|
||||
/**
|
||||
* Determine if the shuttle is currently at a stop.
|
||||
* If `true`, then calling `getShuttleLastStopArrival` will get
|
||||
* the stop the shuttle is currently at.
|
||||
* @param shuttleId
|
||||
*/
|
||||
checkIfShuttleIsAtStop(shuttleId: string): Promise<boolean>;
|
||||
|
||||
/**
|
||||
* Get the stop that the shuttle is currently at, if it's the shuttle's
|
||||
* next stop based on the "last stop" the shuttle was at. If there was no
|
||||
* "last stop" for the shuttle, it may return any stop on the shuttle's route.
|
||||
*
|
||||
* @param shuttle
|
||||
* @param canReturnShuttleCurrentStop If set to true, and the shuttle's "last stop"
|
||||
* matches the arrived stop, continue to return the arrived stop.
|
||||
* Otherwise, only return the shuttle's next stop.
|
||||
* This flag has no effect if the shuttle has not had a "last stop".
|
||||
* @returns
|
||||
*/
|
||||
getArrivedStopIfNextStop(shuttle: IShuttle, canReturnShuttleCurrentStop: boolean): Promise<IStop | undefined>;
|
||||
}
|
||||
40
src/repositories/shuttle/ShuttleGetterSetterRepository.ts
Normal file
40
src/repositories/shuttle/ShuttleGetterSetterRepository.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
// If types match closely, we can use TypeScript "casting"
|
||||
// to convert from data repo to GraphQL schema
|
||||
|
||||
import { ShuttleGetterRepository, ShuttleTravelTimeDataIdentifier, ShuttleTravelTimeDateFilterArguments } from "./ShuttleGetterRepository";
|
||||
import { IOrderedStop, IRoute, IShuttle, IStop } from "../../entities/ShuttleRepositoryEntities";
|
||||
|
||||
/**
|
||||
* ShuttleGetterRepository interface for data derived from Passio API.
|
||||
* The repository is not designed to have write locks in place.
|
||||
* Objects passed from/to the repository should be treated
|
||||
* as disposable.
|
||||
*/
|
||||
export interface ShuttleGetterSetterRepository extends ShuttleGetterRepository {
|
||||
// Setter methods
|
||||
addOrUpdateRoute(route: IRoute): Promise<void>;
|
||||
addOrUpdateShuttle(shuttle: IShuttle, travelTimeTimestamp?: number, referenceCurrentTime?: Date): Promise<void>;
|
||||
addOrUpdateStop(stop: IStop): Promise<void>;
|
||||
addOrUpdateOrderedStop(orderedStop: IOrderedStop): Promise<void>;
|
||||
|
||||
removeRouteIfExists(routeId: string): Promise<IRoute | null>;
|
||||
removeShuttleIfExists(shuttleId: string): Promise<IShuttle | null>;
|
||||
removeStopIfExists(stopId: string): Promise<IStop | null>;
|
||||
removeOrderedStopIfExists(stopId: string, routeId: string): Promise<IOrderedStop | null>;
|
||||
|
||||
clearRouteData(): Promise<void>;
|
||||
clearShuttleData(): Promise<void>;
|
||||
clearStopData(): Promise<void>;
|
||||
clearOrderedStopData(): Promise<void>;
|
||||
|
||||
/**
|
||||
* Get average travel time between two stops based on historical data.
|
||||
* Returns undefined if no data exists for the specified time range.
|
||||
* @param identifier - The route and stop IDs to query
|
||||
* @param dateFilter - The date range to filter data
|
||||
*/
|
||||
getAverageTravelTimeSeconds(
|
||||
identifier: ShuttleTravelTimeDataIdentifier,
|
||||
dateFilter: ShuttleTravelTimeDateFilterArguments
|
||||
): Promise<number | undefined>;
|
||||
}
|
||||
377
src/repositories/shuttle/UnoptimizedInMemoryShuttleRepository.ts
Normal file
377
src/repositories/shuttle/UnoptimizedInMemoryShuttleRepository.ts
Normal file
@@ -0,0 +1,377 @@
|
||||
import EventEmitter from "node:events";
|
||||
import { ShuttleGetterSetterRepository } from "./ShuttleGetterSetterRepository";
|
||||
import { IOrderedStop, IRoute, IShuttle, IStop, shuttleHasArrivedAtStop } from "../../entities/ShuttleRepositoryEntities";
|
||||
import { IEntityWithId } from "../../entities/SharedEntities";
|
||||
import {
|
||||
ShuttleRepositoryEvent,
|
||||
ShuttleRepositoryEventListener,
|
||||
ShuttleRepositoryEventName,
|
||||
ShuttleRepositoryEventPayloads,
|
||||
ShuttleStopArrival,
|
||||
ShuttleTravelTimeDataIdentifier,
|
||||
ShuttleTravelTimeDateFilterArguments,
|
||||
} from "./ShuttleGetterRepository";
|
||||
|
||||
/**
|
||||
* An unoptimized in memory repository.
|
||||
* (I would optimize it with actual data structures, but I'm
|
||||
* switching to another data store later anyways)
|
||||
*/
|
||||
export class UnoptimizedInMemoryShuttleRepository
|
||||
extends EventEmitter
|
||||
implements ShuttleGetterSetterRepository {
|
||||
|
||||
constructor(
|
||||
readonly shuttleStopArrivalDegreeDelta: number = 0.001,
|
||||
) {
|
||||
super()
|
||||
}
|
||||
|
||||
public override on<T extends ShuttleRepositoryEventName>(
|
||||
event: T,
|
||||
listener: ShuttleRepositoryEventListener<T>,
|
||||
): this;
|
||||
public override on(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.on(event, listener);
|
||||
}
|
||||
|
||||
public override once<T extends ShuttleRepositoryEventName>(
|
||||
event: T,
|
||||
listener: ShuttleRepositoryEventListener<T>,
|
||||
): this;
|
||||
public override once(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.once(event, listener);
|
||||
}
|
||||
|
||||
public override off<T extends ShuttleRepositoryEventName>(
|
||||
event: T,
|
||||
listener: ShuttleRepositoryEventListener<T>,
|
||||
): this;
|
||||
public override off(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.off(event, listener);
|
||||
}
|
||||
|
||||
public override addListener<T extends ShuttleRepositoryEventName>(
|
||||
event: T,
|
||||
listener: ShuttleRepositoryEventListener<T>,
|
||||
): this;
|
||||
public override addListener(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.addListener(event, listener);
|
||||
}
|
||||
|
||||
public override removeListener<T extends ShuttleRepositoryEventName>(
|
||||
event: T,
|
||||
listener: ShuttleRepositoryEventListener<T>,
|
||||
): this;
|
||||
public override removeListener(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.removeListener(event, listener);
|
||||
}
|
||||
|
||||
public override emit<T extends ShuttleRepositoryEventName>(
|
||||
event: T,
|
||||
payload: ShuttleRepositoryEventPayloads[T],
|
||||
): boolean;
|
||||
public override emit(event: string | symbol, ...args: any[]): boolean {
|
||||
return super.emit(event, ...args);
|
||||
}
|
||||
|
||||
private stops: IStop[] = [];
|
||||
private routes: IRoute[] = [];
|
||||
private shuttles: IShuttle[] = [];
|
||||
private orderedStops: IOrderedStop[] = [];
|
||||
private shuttleLastStopArrivals: Map<string, ShuttleStopArrival> = new Map();
|
||||
private travelTimeData: Map<string, Array<{ timestamp: number; seconds: number }>> = new Map();
|
||||
private shuttlesAtStop: Set<string> = new Set();
|
||||
|
||||
public async getStops(): Promise<IStop[]> {
|
||||
return this.stops;
|
||||
}
|
||||
|
||||
public async getStopById(stopId: string) {
|
||||
return this.findEntityById(stopId, this.stops);
|
||||
}
|
||||
|
||||
public async getRoutes(): Promise<IRoute[]> {
|
||||
return this.routes;
|
||||
}
|
||||
|
||||
public async getRouteById(routeId: string) {
|
||||
return this.findEntityById(routeId, this.routes);
|
||||
}
|
||||
|
||||
public async getShuttles(): Promise<IShuttle[]> {
|
||||
return this.shuttles;
|
||||
}
|
||||
|
||||
public async getShuttlesByRouteId(routeId: string) {
|
||||
return this.shuttles.filter(shuttle => shuttle.routeId === routeId);
|
||||
}
|
||||
|
||||
public async getShuttleById(shuttleId: string) {
|
||||
return this.findEntityById(shuttleId, this.shuttles);
|
||||
}
|
||||
|
||||
public async getOrderedStopByRouteAndStopId(routeId: string, stopId: string) {
|
||||
return this.findEntityByMatcher<IOrderedStop>((value) => value.routeId === routeId && value.stopId === stopId, this.orderedStops)
|
||||
}
|
||||
|
||||
public async getOrderedStopsByStopId(stopId: string) {
|
||||
return this.orderedStops.filter((value) => value.stopId === stopId);
|
||||
}
|
||||
|
||||
public async getOrderedStopsByRouteId(routeId: string) {
|
||||
return this.orderedStops.filter((value) => value.routeId === routeId);
|
||||
}
|
||||
|
||||
private findEntityById<T extends IEntityWithId>(entityId: string, arrayToSearchIn: T[]) {
|
||||
return this.findEntityByMatcher((value) => value.id === entityId, arrayToSearchIn);
|
||||
}
|
||||
|
||||
private findEntityByMatcher<T>(callback: (value: T) => boolean, arrayToSearchIn: T[]): T | null {
|
||||
const entity = arrayToSearchIn.find(callback);
|
||||
if (!entity) {
|
||||
return null;
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
public async addOrUpdateRoute(route: IRoute): Promise<void> {
|
||||
const index = this.routes.findIndex((r) => r.id === route.id);
|
||||
if (index !== -1) {
|
||||
this.routes[index] = route;
|
||||
} else {
|
||||
this.routes.push(route);
|
||||
}
|
||||
}
|
||||
|
||||
public async addOrUpdateShuttle(
|
||||
shuttle: IShuttle,
|
||||
travelTimeTimestamp = Date.now(),
|
||||
): Promise<void> {
|
||||
const index = this.shuttles.findIndex((s) => s.id === shuttle.id);
|
||||
if (index !== -1) {
|
||||
this.shuttles[index] = shuttle;
|
||||
} else {
|
||||
this.shuttles.push(shuttle);
|
||||
}
|
||||
|
||||
this.emit(ShuttleRepositoryEvent.SHUTTLE_UPDATED, shuttle);
|
||||
|
||||
await this.updateLastStopArrival(shuttle, travelTimeTimestamp);
|
||||
}
|
||||
|
||||
public async addOrUpdateStop(stop: IStop): Promise<void> {
|
||||
const index = this.stops.findIndex((s) => s.id === stop.id);
|
||||
if (index !== -1) {
|
||||
this.stops[index] = stop;
|
||||
} else {
|
||||
this.stops.push(stop);
|
||||
}
|
||||
}
|
||||
|
||||
public async addOrUpdateOrderedStop(orderedStop: IOrderedStop): Promise<void> {
|
||||
const index = this.orderedStops.findIndex((value) => value.stopId === orderedStop.stopId && value.routeId === orderedStop.routeId);
|
||||
if (index !== -1) {
|
||||
this.orderedStops[index] = orderedStop;
|
||||
} else {
|
||||
this.orderedStops.push(orderedStop);
|
||||
}
|
||||
}
|
||||
|
||||
private async updateLastStopArrival(
|
||||
shuttle: IShuttle,
|
||||
travelTimeTimestamp = Date.now(),
|
||||
) {
|
||||
const isAtStop = await this.checkIfShuttleIsAtStop(shuttle.id);
|
||||
|
||||
let arrivedStop: IStop | undefined;
|
||||
|
||||
if (isAtStop) {
|
||||
// Allow retrieval of the shuttle's current stop
|
||||
// Will still return undefined when the shuttle leaves the stop
|
||||
arrivedStop = await this.getArrivedStopIfNextStop(shuttle, true);
|
||||
} else {
|
||||
arrivedStop = await this.getArrivedStopIfNextStop(shuttle, false);
|
||||
}
|
||||
|
||||
|
||||
// Will not fire *any* events if the same stop
|
||||
const lastStop = await this.getShuttleLastStopArrival(shuttle.id);
|
||||
if (lastStop?.stopId === arrivedStop?.id) return;
|
||||
|
||||
if (isAtStop) {
|
||||
if (lastStop) {
|
||||
this.emit(ShuttleRepositoryEvent.SHUTTLE_WILL_LEAVE_STOP, {
|
||||
stopArrivalThatShuttleIsLeaving: lastStop,
|
||||
});
|
||||
}
|
||||
await this.markShuttleAsNotAtStop(shuttle.id);
|
||||
}
|
||||
|
||||
if (arrivedStop) {
|
||||
// stop if same stop
|
||||
const shuttleArrival = {
|
||||
stopId: arrivedStop.id,
|
||||
timestamp: new Date(travelTimeTimestamp),
|
||||
shuttleId: shuttle.id,
|
||||
};
|
||||
this.emit(ShuttleRepositoryEvent.SHUTTLE_WILL_ARRIVE_AT_STOP, {
|
||||
lastStopArrival: lastStop,
|
||||
willArriveAt: shuttleArrival,
|
||||
});
|
||||
await this.markShuttleAsAtStop(shuttleArrival.shuttleId);
|
||||
await this.updateShuttleLastStopArrival(shuttleArrival);
|
||||
}
|
||||
}
|
||||
|
||||
private async markShuttleAsAtStop(shuttleId: string) {
|
||||
this.shuttlesAtStop.add(shuttleId);
|
||||
}
|
||||
|
||||
private async markShuttleAsNotAtStop(shuttleId: string) {
|
||||
this.shuttlesAtStop.delete(shuttleId);
|
||||
}
|
||||
|
||||
public async checkIfShuttleIsAtStop(shuttleId: string) {
|
||||
return this.shuttlesAtStop.has(shuttleId);
|
||||
}
|
||||
|
||||
|
||||
private async updateShuttleLastStopArrival(lastStopArrival: ShuttleStopArrival) {
|
||||
this.shuttleLastStopArrivals.set(lastStopArrival.shuttleId, lastStopArrival);
|
||||
}
|
||||
|
||||
public async getAverageTravelTimeSeconds(
|
||||
{ routeId, fromStopId, toStopId }: ShuttleTravelTimeDataIdentifier,
|
||||
{ from, to }: ShuttleTravelTimeDateFilterArguments,
|
||||
): Promise<number | undefined> {
|
||||
const key = `${routeId}:${fromStopId}:${toStopId}`;
|
||||
const dataPoints = this.travelTimeData.get(key);
|
||||
|
||||
if (!dataPoints || dataPoints.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const fromTimestamp = from.getTime();
|
||||
const toTimestamp = to.getTime();
|
||||
|
||||
const filteredPoints = dataPoints.filter(
|
||||
(point) => point.timestamp >= fromTimestamp && point.timestamp <= toTimestamp
|
||||
);
|
||||
|
||||
if (filteredPoints.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const sum = filteredPoints.reduce((acc, point) => acc + point.seconds, 0);
|
||||
return sum / filteredPoints.length;
|
||||
}
|
||||
|
||||
public async getArrivedStopIfNextStop(
|
||||
shuttle: IShuttle,
|
||||
canReturnShuttleCurrentStop: boolean = false,
|
||||
): Promise<IStop | undefined> {
|
||||
const degreeDelta = this.shuttleStopArrivalDegreeDelta;
|
||||
|
||||
const lastStopArrival = await this.getShuttleLastStopArrival(shuttle.id);
|
||||
if (lastStopArrival) {
|
||||
// Return the shuttle's current stop depending on the flag
|
||||
if (canReturnShuttleCurrentStop) {
|
||||
const lastStop = await this.getStopById(lastStopArrival.stopId);
|
||||
if (lastStop && shuttleHasArrivedAtStop(shuttle, lastStop, degreeDelta)) {
|
||||
return lastStop;
|
||||
}
|
||||
}
|
||||
|
||||
const lastOrderedStop = await this.getOrderedStopByRouteAndStopId(shuttle.routeId, lastStopArrival.stopId);
|
||||
const orderedStopAfter = lastOrderedStop?.nextStop;
|
||||
if (orderedStopAfter) {
|
||||
const stopAfter = await this.getStopById(orderedStopAfter.stopId);
|
||||
if (stopAfter && shuttleHasArrivedAtStop(shuttle, stopAfter, degreeDelta)) {
|
||||
return stopAfter;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const orderedStops = await this.getOrderedStopsByRouteId(shuttle.routeId);
|
||||
|
||||
for (const orderedStop of orderedStops) {
|
||||
const stop = await this.getStopById(orderedStop.stopId);
|
||||
if (stop != null && shuttleHasArrivedAtStop(shuttle, stop, degreeDelta)) {
|
||||
return stop;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
public async getShuttleLastStopArrival(shuttleId: string): Promise<ShuttleStopArrival | undefined> {
|
||||
return this.shuttleLastStopArrivals.get(shuttleId);
|
||||
}
|
||||
|
||||
private async removeEntityByMatcherIfExists<T>(callback: (value: T) => boolean, arrayToSearchIn: T[]) {
|
||||
const index = arrayToSearchIn.findIndex(callback);
|
||||
if (index > -1) {
|
||||
const entityToReturn = arrayToSearchIn[index];
|
||||
arrayToSearchIn.splice(index, 1);
|
||||
return entityToReturn;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private async removeEntityByIdIfExists<T extends IEntityWithId>(entityId: string, arrayToSearchIn: T[]) {
|
||||
return await this.removeEntityByMatcherIfExists((value) => value.id === entityId, arrayToSearchIn);
|
||||
}
|
||||
|
||||
public async removeRouteIfExists(routeId: string): Promise<IRoute | null> {
|
||||
return await this.removeEntityByIdIfExists(routeId, this.routes);
|
||||
}
|
||||
|
||||
public async removeShuttleIfExists(shuttleId: string): Promise<IShuttle | null> {
|
||||
const shuttle = await this.removeEntityByIdIfExists(shuttleId, this.shuttles);
|
||||
if (shuttle != null) {
|
||||
this.emit(ShuttleRepositoryEvent.SHUTTLE_REMOVED, shuttle);
|
||||
this.shuttlesAtStop.delete(shuttleId);
|
||||
await this.removeShuttleLastStopIfExists(shuttleId);
|
||||
}
|
||||
return shuttle;
|
||||
}
|
||||
|
||||
public async removeStopIfExists(stopId: string): Promise<IStop | null> {
|
||||
return await this.removeEntityByIdIfExists(stopId, this.stops);
|
||||
}
|
||||
|
||||
public async removeOrderedStopIfExists(stopId: string, routeId: string): Promise<IOrderedStop | null> {
|
||||
return await this.removeEntityByMatcherIfExists((orderedStop) => {
|
||||
return orderedStop.stopId === stopId
|
||||
&& orderedStop.routeId === routeId
|
||||
}, this.orderedStops);
|
||||
}
|
||||
|
||||
private async removeShuttleLastStopIfExists(shuttleId: string) {
|
||||
this.shuttleLastStopArrivals.delete(shuttleId);
|
||||
}
|
||||
|
||||
public async clearShuttleData(): Promise<void> {
|
||||
this.shuttles = [];
|
||||
this.shuttlesAtStop.clear();
|
||||
await this.clearShuttleLastStopData();
|
||||
}
|
||||
|
||||
public async clearOrderedStopData(): Promise<void> {
|
||||
this.orderedStops = [];
|
||||
}
|
||||
|
||||
public async clearRouteData(): Promise<void> {
|
||||
this.routes = [];
|
||||
}
|
||||
|
||||
public async clearStopData(): Promise<void> {
|
||||
this.stops = [];
|
||||
}
|
||||
|
||||
private async clearShuttleLastStopData(): Promise<void> {
|
||||
this.shuttleLastStopArrivals.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,882 @@
|
||||
import { afterEach, beforeEach, describe, expect, jest, test } from "@jest/globals";
|
||||
import { createClient, RedisClientType } from "redis";
|
||||
import { UnoptimizedInMemoryShuttleRepository } from "../UnoptimizedInMemoryShuttleRepository";
|
||||
import { ShuttleGetterSetterRepository } from "../ShuttleGetterSetterRepository";
|
||||
import { RedisShuttleRepository } from "../RedisShuttleRepository";
|
||||
import {
|
||||
generateMockOrderedStops,
|
||||
generateMockRoutes,
|
||||
generateMockShuttles,
|
||||
generateMockStops,
|
||||
} from "../../../../testHelpers/mockDataGenerators";
|
||||
import { RepositoryHolder } from "../../../../testHelpers/RepositoryHolder";
|
||||
import { setupRouteAndOrderedStopsForShuttleRepository } from "../../../../testHelpers/setupRouteAndOrderedStopsForShuttleRepository";
|
||||
import { ShuttleRepositoryEvent } from "../ShuttleGetterRepository";
|
||||
|
||||
class UnoptimizedInMemoryShuttleRepositoryHolder implements RepositoryHolder<ShuttleGetterSetterRepository> {
|
||||
name = 'UnoptimizedInMemoryShuttleRepository';
|
||||
factory = async () => {
|
||||
return new UnoptimizedInMemoryShuttleRepository();
|
||||
};
|
||||
teardown = async () => { };
|
||||
}
|
||||
|
||||
class RedisShuttleRepositoryHolder implements RepositoryHolder<ShuttleGetterSetterRepository> {
|
||||
repo: RedisShuttleRepository | undefined;
|
||||
redisClient: RedisClientType | undefined;
|
||||
|
||||
name = 'RedisShuttleRepository';
|
||||
factory = async () => {
|
||||
this.redisClient = createClient({
|
||||
url: process.env.REDIS_URL,
|
||||
});
|
||||
await this.redisClient.connect();
|
||||
this.repo = new RedisShuttleRepository(this.redisClient);
|
||||
return this.repo;
|
||||
};
|
||||
teardown = async () => {
|
||||
if (this.redisClient) {
|
||||
await this.redisClient.flushAll();
|
||||
await this.redisClient.disconnect();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const repositoryImplementations = [
|
||||
new UnoptimizedInMemoryShuttleRepositoryHolder(),
|
||||
new RedisShuttleRepositoryHolder(),
|
||||
];
|
||||
|
||||
describe.each(repositoryImplementations)('$name', (holder) => {
|
||||
let repository: ShuttleGetterSetterRepository;
|
||||
|
||||
beforeEach(async () => {
|
||||
repository = await holder.factory();
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await holder.teardown();
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
describe("getStops", () => {
|
||||
test("gets all stops in the repository", async () => {
|
||||
const mockStops = generateMockStops();
|
||||
for (const stop of mockStops) {
|
||||
await repository.addOrUpdateStop(stop);
|
||||
}
|
||||
|
||||
const result = await repository.getStops();
|
||||
expect(result).toHaveLength(mockStops.length);
|
||||
expect(result).toEqual(expect.arrayContaining(mockStops));
|
||||
});
|
||||
|
||||
test("returns an empty list if there are no stops for the given system ID", async () => {
|
||||
const result = await repository.getStops();
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getStopById", () => {
|
||||
test("gets a stop by ID if it exists", async () => {
|
||||
const mockStops = generateMockStops();
|
||||
const mockStop = mockStops[0];
|
||||
await repository.addOrUpdateStop(mockStop);
|
||||
|
||||
const result = await repository.getStopById("st1");
|
||||
expect(result).toEqual(mockStop);
|
||||
});
|
||||
|
||||
test("returns null if the stop does not exist", async () => {
|
||||
const result = await repository.getStopById("nonexistent-stop");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getRoutes", () => {
|
||||
test("gets all routes for a specific system ID", async () => {
|
||||
const mockRoutes = generateMockRoutes();
|
||||
for (const route of mockRoutes) {
|
||||
await repository.addOrUpdateRoute(route);
|
||||
}
|
||||
|
||||
const result = await repository.getRoutes();
|
||||
expect(result).toHaveLength(mockRoutes.length);
|
||||
expect(result).toEqual(expect.arrayContaining(mockRoutes));
|
||||
});
|
||||
|
||||
test("returns an empty list if there are no routes for the system ID", async () => {
|
||||
const result = await repository.getRoutes();
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getRouteById", () => {
|
||||
test("gets a route by ID if it exists", async () => {
|
||||
const mockRoutes = generateMockRoutes();
|
||||
const mockRoute = mockRoutes[0];
|
||||
await repository.addOrUpdateRoute(mockRoute);
|
||||
|
||||
const result = await repository.getRouteById("r1");
|
||||
expect(result).toEqual(mockRoute);
|
||||
});
|
||||
|
||||
test("returns null if the route does not exist", async () => {
|
||||
const result = await repository.getRouteById("nonexistent-route");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getShuttles", () => {
|
||||
test("gets all shuttles for a specific system ID", async () => {
|
||||
const mockShuttles = generateMockShuttles();
|
||||
for (const shuttle of mockShuttles) {
|
||||
await repository.addOrUpdateShuttle(shuttle);
|
||||
}
|
||||
|
||||
const result = await repository.getShuttles();
|
||||
expect(result).toHaveLength(mockShuttles.length);
|
||||
expect(result).toEqual(expect.arrayContaining(mockShuttles));
|
||||
});
|
||||
|
||||
test("returns an empty list if there are no shuttles for the system ID", async () => {
|
||||
const result = await repository.getShuttles();
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getShuttlesByRouteId", () => {
|
||||
test("gets all shuttles for a specific route ID", async () => {
|
||||
const mockShuttles = generateMockShuttles();
|
||||
for (const shuttle of mockShuttles) {
|
||||
await repository.addOrUpdateShuttle(shuttle);
|
||||
}
|
||||
|
||||
const result = await repository.getShuttlesByRouteId("r1");
|
||||
expect(result).toEqual(mockShuttles.filter((sh) => sh.routeId === "r1"));
|
||||
});
|
||||
|
||||
test("returns an empty list if there are no shuttles for the route ID", async () => {
|
||||
const result = await repository.getShuttlesByRouteId("nonexistent-route");
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getShuttleById", () => {
|
||||
test("gets a shuttle by ID if it exists", async () => {
|
||||
const mockShuttles = generateMockShuttles();
|
||||
for (const shuttle of mockShuttles) {
|
||||
await repository.addOrUpdateShuttle(shuttle);
|
||||
}
|
||||
|
||||
const result = await repository.getShuttleById("sh2");
|
||||
expect(result).toEqual(mockShuttles[1]);
|
||||
});
|
||||
|
||||
test("returns null if the shuttle doesn't exist", async () => {
|
||||
const result = await repository.getShuttleById("nonexistent-id");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getOrderedStopByRouteAndStopId", () => {
|
||||
test("gets an ordered stop by route ID and stop ID", async () => {
|
||||
const mockOrderedStops = generateMockOrderedStops();
|
||||
for (const orderedStop of mockOrderedStops) {
|
||||
await repository.addOrUpdateOrderedStop(orderedStop);
|
||||
}
|
||||
|
||||
const mockOrderedStop = mockOrderedStops[0];
|
||||
const { routeId, stopId } = mockOrderedStop;
|
||||
|
||||
const result = await repository.getOrderedStopByRouteAndStopId(routeId, stopId);
|
||||
expect(result).toEqual(mockOrderedStop);
|
||||
});
|
||||
|
||||
test("returns null if no ordered stop matches the given route ID and stop ID", async () => {
|
||||
const result = await repository.getOrderedStopByRouteAndStopId("nonexistent-route", "nonexistent-stop");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getOrderedStopsByStopId", () => {
|
||||
test("gets all ordered stops for a specific stop ID", async () => {
|
||||
const mockOrderedStops = generateMockOrderedStops();
|
||||
for (const orderedStop of mockOrderedStops) {
|
||||
await repository.addOrUpdateOrderedStop(orderedStop);
|
||||
}
|
||||
|
||||
const result = await repository.getOrderedStopsByStopId("st1");
|
||||
const expected = mockOrderedStops.filter((os) => os.stopId === "st1");
|
||||
expect(result).toHaveLength(expected.length);
|
||||
expect(result).toEqual(expect.arrayContaining(expected));
|
||||
});
|
||||
|
||||
test("returns an empty list if there are no ordered stops for the stop ID", async () => {
|
||||
const result = await repository.getOrderedStopsByStopId("nonexistent-stop");
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getOrderedStopsByRouteId", () => {
|
||||
test("gets all ordered stops for a specific route ID", async () => {
|
||||
const mockOrderedStops = generateMockOrderedStops();
|
||||
for (const orderedStop of mockOrderedStops) {
|
||||
await repository.addOrUpdateOrderedStop(orderedStop);
|
||||
}
|
||||
|
||||
const result = await repository.getOrderedStopsByRouteId("r1");
|
||||
const expected = mockOrderedStops.filter((os) => os.routeId === "r1");
|
||||
expect(result).toHaveLength(expected.length);
|
||||
expect(result).toEqual(expect.arrayContaining(expected));
|
||||
});
|
||||
|
||||
test("returns an empty list if there are no ordered stops for the route ID", async () => {
|
||||
const result = await repository.getOrderedStopsByRouteId("nonexistent-route");
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("addOrUpdateRoute", () => {
|
||||
test("adds a new route if nonexistent", async () => {
|
||||
const mockRoutes = generateMockRoutes();
|
||||
const newRoute = mockRoutes[0];
|
||||
|
||||
await repository.addOrUpdateRoute(newRoute);
|
||||
|
||||
const result = await repository.getRoutes();
|
||||
expect(result).toEqual([newRoute]);
|
||||
});
|
||||
|
||||
test("updates an existing route if it exists", async () => {
|
||||
const mockRoutes = generateMockRoutes();
|
||||
const existingRoute = mockRoutes[0];
|
||||
const updatedRoute = structuredClone(existingRoute);
|
||||
updatedRoute.name = "Updated Route";
|
||||
|
||||
await repository.addOrUpdateRoute(existingRoute);
|
||||
await repository.addOrUpdateRoute(updatedRoute);
|
||||
|
||||
const result = await repository.getRoutes();
|
||||
expect(result).toEqual([updatedRoute]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("addOrUpdateShuttle", () => {
|
||||
test("adds a new shuttle if nonexistent", async () => {
|
||||
const mockShuttles = generateMockShuttles();
|
||||
const newShuttle = mockShuttles[0];
|
||||
|
||||
await repository.addOrUpdateShuttle(newShuttle);
|
||||
|
||||
const result = await repository.getShuttles();
|
||||
expect(result).toEqual([newShuttle]);
|
||||
});
|
||||
|
||||
test("updates an existing shuttle if it exists", async () => {
|
||||
const mockShuttles = generateMockShuttles();
|
||||
const existingShuttle = mockShuttles[0];
|
||||
const updatedShuttle = structuredClone(existingShuttle);
|
||||
updatedShuttle.name = "Updated Shuttle";
|
||||
|
||||
await repository.addOrUpdateShuttle(existingShuttle);
|
||||
await repository.addOrUpdateShuttle(updatedShuttle);
|
||||
|
||||
const result = await repository.getShuttles();
|
||||
expect(result).toEqual([updatedShuttle]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("addOrUpdateStop", () => {
|
||||
test("adds a new stop if nonexistent", async () => {
|
||||
const mockStops = generateMockStops();
|
||||
const newStop = mockStops[0];
|
||||
|
||||
await repository.addOrUpdateStop(newStop);
|
||||
|
||||
const result = await repository.getStops();
|
||||
expect(result).toEqual([newStop]);
|
||||
});
|
||||
|
||||
test("updates an existing stop if it exists", async () => {
|
||||
const mockStops = generateMockStops();
|
||||
const existingStop = mockStops[0];
|
||||
const updatedStop = structuredClone(existingStop);
|
||||
updatedStop.name = "Updated Stop";
|
||||
|
||||
await repository.addOrUpdateStop(existingStop);
|
||||
await repository.addOrUpdateStop(updatedStop);
|
||||
|
||||
const result = await repository.getStops();
|
||||
expect(result).toEqual([updatedStop]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("addOrUpdateOrderedStop", () => {
|
||||
test("adds a new ordered stop if nonexistent", async () => {
|
||||
const mockOrderedStops = generateMockOrderedStops();
|
||||
const newOrderedStop = mockOrderedStops[0];
|
||||
|
||||
await repository.addOrUpdateOrderedStop(newOrderedStop);
|
||||
|
||||
const result = await repository.getOrderedStopsByRouteId(newOrderedStop.routeId);
|
||||
expect(result).toEqual([newOrderedStop]);
|
||||
});
|
||||
|
||||
test("updates an existing ordered stop if it exists", async () => {
|
||||
const mockOrderedStops = generateMockOrderedStops();
|
||||
const existingOrderedStop = mockOrderedStops[0];
|
||||
const updatedOrderedStop = structuredClone(existingOrderedStop);
|
||||
updatedOrderedStop.position = 5;
|
||||
|
||||
await repository.addOrUpdateOrderedStop(existingOrderedStop);
|
||||
await repository.addOrUpdateOrderedStop(updatedOrderedStop);
|
||||
|
||||
const result = await repository.getOrderedStopsByRouteId(existingOrderedStop.routeId);
|
||||
expect(result).toEqual([updatedOrderedStop]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("removeRouteIfExists", () => {
|
||||
test("removes route given ID", async () => {
|
||||
const systemId = "1";
|
||||
const mockRoutes = generateMockRoutes();
|
||||
await Promise.all(mockRoutes.map(async (route) => {
|
||||
route.systemId = systemId;
|
||||
await repository.addOrUpdateRoute(route);
|
||||
}));
|
||||
|
||||
const routeToRemove = mockRoutes[0];
|
||||
await repository.removeRouteIfExists(routeToRemove.id);
|
||||
|
||||
const remainingRoutes = await repository.getRoutes();
|
||||
expect(remainingRoutes).toHaveLength(mockRoutes.length - 1);
|
||||
});
|
||||
|
||||
test("does nothing if route doesn't exist", async () => {
|
||||
const systemId = "1";
|
||||
const mockRoutes = generateMockRoutes();
|
||||
await Promise.all(mockRoutes.map(async (route) => {
|
||||
route.systemId = systemId;
|
||||
await repository.addOrUpdateRoute(route);
|
||||
}));
|
||||
|
||||
await repository.removeRouteIfExists("nonexistent-id");
|
||||
|
||||
const remainingRoutes = await repository.getRoutes();
|
||||
expect(remainingRoutes).toHaveLength(mockRoutes.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe("removeShuttleIfExists", () => {
|
||||
test("removes shuttle given ID", async () => {
|
||||
const systemId = "1";
|
||||
const mockShuttles = generateMockShuttles();
|
||||
await Promise.all(mockShuttles.map(async (shuttle) => {
|
||||
shuttle.systemId = systemId;
|
||||
await repository.addOrUpdateShuttle(shuttle);
|
||||
}));
|
||||
|
||||
const shuttleToRemove = mockShuttles[0];
|
||||
await repository.removeShuttleIfExists(shuttleToRemove.id);
|
||||
|
||||
const remainingShuttles = await repository.getShuttles();
|
||||
expect(remainingShuttles).toHaveLength(mockShuttles.length - 1);
|
||||
});
|
||||
|
||||
test("removes shuttle last stop if exists", async () => {
|
||||
const { route, stop1, systemId } = await setupRouteAndOrderedStops();
|
||||
const mockShuttle = generateMockShuttles()[0];
|
||||
mockShuttle.routeId = route.id;
|
||||
mockShuttle.coordinates = stop1.coordinates;
|
||||
mockShuttle.systemId = systemId;
|
||||
|
||||
await repository.addOrUpdateShuttle(mockShuttle);
|
||||
await repository.removeShuttleIfExists(mockShuttle.id);
|
||||
|
||||
const lastStopData = await repository.getShuttleLastStopArrival(mockShuttle.id);
|
||||
expect(lastStopData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("does nothing if shuttle doesn't exist", async () => {
|
||||
const systemId = "1";
|
||||
const mockShuttles = generateMockShuttles();
|
||||
await Promise.all(mockShuttles.map(async (shuttle) => {
|
||||
shuttle.systemId = systemId;
|
||||
await repository.addOrUpdateShuttle(shuttle);
|
||||
}));
|
||||
|
||||
await repository.removeShuttleIfExists("nonexistent-id");
|
||||
|
||||
const remainingShuttles = await repository.getShuttles();
|
||||
expect(remainingShuttles).toHaveLength(mockShuttles.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe("removeStopIfExists", () => {
|
||||
test("removes stop given ID", async () => {
|
||||
const systemId = "1";
|
||||
const mockStops = generateMockStops();
|
||||
await Promise.all(mockStops.map(async (stop) => {
|
||||
stop.systemId = systemId;
|
||||
await repository.addOrUpdateStop(stop);
|
||||
}));
|
||||
|
||||
const stopToRemove = mockStops[0];
|
||||
await repository.removeStopIfExists(stopToRemove.id);
|
||||
|
||||
const remainingStops = await repository.getStops();
|
||||
expect(remainingStops).toHaveLength(mockStops.length - 1);
|
||||
});
|
||||
|
||||
test("does nothing if stop doesn't exist", async () => {
|
||||
const systemId = "1";
|
||||
const mockStops = generateMockStops();
|
||||
await Promise.all(mockStops.map(async (stop) => {
|
||||
stop.systemId = systemId;
|
||||
await repository.addOrUpdateStop(stop);
|
||||
}));
|
||||
|
||||
await repository.removeStopIfExists("nonexistent-id");
|
||||
|
||||
const remainingStops = await repository.getStops();
|
||||
expect(remainingStops).toHaveLength(mockStops.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe("removeOrderedStopIfExists", () => {
|
||||
test("removes ordered stop given stop ID and route ID", async () => {
|
||||
let mockOrderedStops = generateMockOrderedStops();
|
||||
const routeId = mockOrderedStops[0].routeId;
|
||||
mockOrderedStops = mockOrderedStops.filter((orderedStop) => orderedStop.routeId === routeId);
|
||||
await Promise.all(mockOrderedStops.map(async (stop) => {
|
||||
stop.routeId = routeId;
|
||||
await repository.addOrUpdateOrderedStop(stop);
|
||||
}));
|
||||
|
||||
const orderedStopToRemove = mockOrderedStops[0];
|
||||
await repository.removeOrderedStopIfExists(orderedStopToRemove.stopId, orderedStopToRemove.routeId);
|
||||
|
||||
const remainingOrderedStops = await repository.getOrderedStopsByRouteId(routeId);
|
||||
expect(remainingOrderedStops).toHaveLength(mockOrderedStops.length - 1);
|
||||
});
|
||||
|
||||
test("does nothing if ordered stop doesn't exist", async () => {
|
||||
let mockOrderedStops = generateMockOrderedStops();
|
||||
const routeId = mockOrderedStops[0].routeId;
|
||||
mockOrderedStops = mockOrderedStops.filter((orderedStop) => orderedStop.routeId === routeId);
|
||||
await Promise.all(mockOrderedStops.map(async (stop) => {
|
||||
stop.routeId = routeId;
|
||||
await repository.addOrUpdateOrderedStop(stop);
|
||||
}));
|
||||
|
||||
await repository.removeOrderedStopIfExists("nonexistent-stop-id", "nonexistent-route-id");
|
||||
|
||||
const remainingOrderedStops = await repository.getOrderedStopsByRouteId(routeId);
|
||||
expect(remainingOrderedStops).toHaveLength(mockOrderedStops.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe("clearShuttleData", () => {
|
||||
test("clears all shuttles from the repository", async () => {
|
||||
const mockShuttles = generateMockShuttles();
|
||||
for (const shuttle of mockShuttles) {
|
||||
await repository.addOrUpdateShuttle(shuttle);
|
||||
}
|
||||
|
||||
await repository.clearShuttleData();
|
||||
|
||||
const result = await repository.getShuttles();
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
test("also clears last stop data", async () => {
|
||||
const { route, stop1, stop2, systemId } = await setupRouteAndOrderedStops();
|
||||
|
||||
const mockShuttles = generateMockShuttles();
|
||||
mockShuttles[0].coordinates = stop1.coordinates;
|
||||
mockShuttles[1].coordinates = stop2.coordinates;
|
||||
|
||||
for (const shuttle of mockShuttles) {
|
||||
shuttle.routeId = route.id;
|
||||
shuttle.systemId = systemId;
|
||||
|
||||
await repository.addOrUpdateShuttle(shuttle);
|
||||
}
|
||||
|
||||
await repository.clearShuttleData();
|
||||
|
||||
for (const shuttle of mockShuttles) {
|
||||
const result = await repository.getShuttleLastStopArrival(shuttle.id);
|
||||
expect(result).toBeUndefined();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("clearOrderedStopData", () => {
|
||||
test("clears all ordered stops from the repository", async () => {
|
||||
const mockOrderedStops = generateMockOrderedStops();
|
||||
for (const system of mockOrderedStops) {
|
||||
await repository.addOrUpdateOrderedStop(system);
|
||||
}
|
||||
|
||||
await repository.clearOrderedStopData();
|
||||
|
||||
const result = await repository.getOrderedStopsByRouteId("route1");
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("clearRouteData", () => {
|
||||
test("clears all routes from the repository", async () => {
|
||||
const mockRoutes = generateMockRoutes();
|
||||
for (const route of mockRoutes) {
|
||||
await repository.addOrUpdateRoute(route);
|
||||
}
|
||||
|
||||
await repository.clearRouteData();
|
||||
|
||||
const result = await repository.getRoutes();
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("clearStopData", () => {
|
||||
test("clears all stops from the repository", async () => {
|
||||
const mockStops = generateMockStops();
|
||||
for (const stop of mockStops) {
|
||||
await repository.addOrUpdateStop(stop);
|
||||
}
|
||||
|
||||
await repository.clearStopData();
|
||||
|
||||
const result = await repository.getStops();
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// Helper function for setting up routes and ordered stops for shuttle tracking tests
|
||||
async function setupRouteAndOrderedStops() {
|
||||
return await setupRouteAndOrderedStopsForShuttleRepository(repository);
|
||||
}
|
||||
|
||||
describe("addOrUpdateShuttle with shuttle tracking", () => {
|
||||
test("updates the shuttle's last stop arrival if shuttle is at a stop", async () => {
|
||||
const { stop2, sampleShuttleNotInRepository: shuttle } = await setupRouteAndOrderedStops();
|
||||
|
||||
await repository.addOrUpdateShuttle(shuttle);
|
||||
const lastStop = await repository.getShuttleLastStopArrival(shuttle.id);
|
||||
expect(lastStop?.stopId).toEqual(stop2.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getArrivedStopIfExists", () => {
|
||||
test("gets any stop that the shuttle is currently at, if the shuttle has not had a last stop", async () => {
|
||||
const { sampleShuttleNotInRepository: shuttle } = await setupRouteAndOrderedStops();
|
||||
|
||||
const result = await repository.getArrivedStopIfNextStop(shuttle, false);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.id).toBe("st2");
|
||||
expect(result?.name).toBe("Stop 2");
|
||||
});
|
||||
|
||||
test("returns undefined if shuttle is not currently at a stop", async () => {
|
||||
const { sampleShuttleNotInRepository } = await setupRouteAndOrderedStops();
|
||||
const shuttle = { ...sampleShuttleNotInRepository, coordinates: { latitude: 12.5, longitude: 22.5 } }; // Not at any stop
|
||||
|
||||
const result = await repository.getArrivedStopIfNextStop(shuttle, false);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
test("only gets the shuttle's next stop if shuttle has previously arrived at a stop", async () => {
|
||||
const { sampleShuttleNotInRepository: shuttle, stop1, stop2 } = await setupRouteAndOrderedStops();
|
||||
|
||||
shuttle.coordinates = stop1.coordinates;
|
||||
await repository.addOrUpdateShuttle(shuttle);
|
||||
|
||||
let result = await repository.getArrivedStopIfNextStop(shuttle, false);
|
||||
expect(result).toBeUndefined();
|
||||
|
||||
shuttle.coordinates = stop2.coordinates;
|
||||
result = await repository.getArrivedStopIfNextStop(shuttle, false);
|
||||
expect(result).not.toBeUndefined();
|
||||
});
|
||||
|
||||
test("returns the shuttle's currently arrived stop if flag passed", async () => {
|
||||
const { sampleShuttleNotInRepository: shuttle, stop1 } = await setupRouteAndOrderedStops();
|
||||
|
||||
shuttle.coordinates = stop1.coordinates;
|
||||
await repository.addOrUpdateShuttle(shuttle);
|
||||
|
||||
const result = await repository.getArrivedStopIfNextStop(shuttle, true);
|
||||
expect(result?.id === stop1.id)
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe("getShuttleLastStopArrival", () => {
|
||||
test("gets the shuttle's last stop if existing in the data", async () => {
|
||||
const { stop1, sampleShuttleNotInRepository: shuttle } = await setupRouteAndOrderedStops();
|
||||
shuttle.coordinates = stop1.coordinates;
|
||||
|
||||
const stopArrivalTime = new Date("2024-01-15T10:30:00Z");
|
||||
await repository.addOrUpdateShuttle(shuttle, stopArrivalTime.getTime());
|
||||
|
||||
const result = await repository.getShuttleLastStopArrival(shuttle.id);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.stopId).toBe(stop1.id);
|
||||
expect(result?.timestamp.getTime()).toBe(stopArrivalTime.getTime());
|
||||
});
|
||||
|
||||
test("returns undefined if the data has never been initialized", async () => {
|
||||
const mockShuttles = generateMockShuttles();
|
||||
const shuttle = mockShuttles[0];
|
||||
|
||||
const result = await repository.getShuttleLastStopArrival(shuttle.id);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
test("returns the most recent stop arrival when updated multiple times", async () => {
|
||||
const { stop1, stop2, sampleShuttleNotInRepository: shuttle } = await setupRouteAndOrderedStops();
|
||||
shuttle.coordinates = stop1.coordinates;
|
||||
|
||||
const firstArrivalTime = new Date("2024-01-15T10:30:00Z");
|
||||
await repository.addOrUpdateShuttle(shuttle, firstArrivalTime.getTime());
|
||||
|
||||
shuttle.coordinates = stop2.coordinates;
|
||||
const secondArrivalTime = new Date("2024-01-15T10:35:00Z");
|
||||
await repository.addOrUpdateShuttle(shuttle, secondArrivalTime.getTime());
|
||||
|
||||
const result = await repository.getShuttleLastStopArrival(shuttle.id);
|
||||
|
||||
expect(result).toBeDefined();
|
||||
expect(result?.stopId).toBe(stop2.id);
|
||||
expect(result?.timestamp.getTime()).toBe(secondArrivalTime.getTime());
|
||||
});
|
||||
});
|
||||
|
||||
describe("SHUTTLE_UPDATED event", () => {
|
||||
test("emits SHUTTLE_UPDATED event when shuttles are added or updated", async () => {
|
||||
const mockListener = jest.fn();
|
||||
repository.on(ShuttleRepositoryEvent.SHUTTLE_UPDATED, mockListener);
|
||||
|
||||
const mockShuttles = generateMockShuttles();
|
||||
for (const shuttle of mockShuttles) {
|
||||
await repository.addOrUpdateShuttle(shuttle);
|
||||
}
|
||||
|
||||
expect(mockListener).toHaveBeenCalledTimes(mockShuttles.length);
|
||||
expect(mockListener).toHaveBeenCalledWith(mockShuttles[0]);
|
||||
expect(mockListener).toHaveBeenCalledWith(mockShuttles[mockShuttles.length - 1]);
|
||||
});
|
||||
|
||||
test("does not notify listener after it has been removed", async () => {
|
||||
const mockListener = jest.fn();
|
||||
repository.on(ShuttleRepositoryEvent.SHUTTLE_UPDATED, mockListener);
|
||||
|
||||
const mockShuttles = generateMockShuttles();
|
||||
|
||||
repository.off(ShuttleRepositoryEvent.SHUTTLE_UPDATED, mockListener);
|
||||
await repository.addOrUpdateShuttle(mockShuttles[0]);
|
||||
expect(mockListener).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
test("stops notifying specific listener after removal but continues for others", async () => {
|
||||
const mockListener1 = jest.fn();
|
||||
const mockListener2 = jest.fn();
|
||||
repository.on(ShuttleRepositoryEvent.SHUTTLE_UPDATED, mockListener1);
|
||||
repository.on(ShuttleRepositoryEvent.SHUTTLE_UPDATED, mockListener2);
|
||||
|
||||
const mockShuttles = generateMockShuttles();
|
||||
await repository.addOrUpdateShuttle(mockShuttles[0]);
|
||||
|
||||
repository.off(ShuttleRepositoryEvent.SHUTTLE_UPDATED, mockListener1);
|
||||
|
||||
await repository.addOrUpdateShuttle(mockShuttles[mockShuttles.length - 1]);
|
||||
|
||||
expect(mockListener1).toHaveBeenCalledTimes(1);
|
||||
expect(mockListener1).toHaveBeenCalledWith(mockShuttles[0]);
|
||||
expect(mockListener1).not.toHaveBeenCalledWith(mockShuttles[mockShuttles.length - 1]);
|
||||
|
||||
expect(mockListener2).toHaveBeenCalledTimes(2);
|
||||
expect(mockListener2).toHaveBeenCalledWith(mockShuttles[0]);
|
||||
expect(mockListener2).toHaveBeenCalledWith(mockShuttles[mockShuttles.length - 1]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("SHUTTLE_REMOVED event", () => {
|
||||
test("emits SHUTTLE_REMOVED event when a shuttle is removed", async () => {
|
||||
const mockShuttles = generateMockShuttles();
|
||||
const shuttleToRemove = mockShuttles[0];
|
||||
const listener = jest.fn();
|
||||
repository.on(ShuttleRepositoryEvent.SHUTTLE_REMOVED, listener);
|
||||
|
||||
await repository.addOrUpdateShuttle(shuttleToRemove);
|
||||
await repository.removeShuttleIfExists(shuttleToRemove.id);
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
expect(listener).toHaveBeenCalledWith(shuttleToRemove);
|
||||
});
|
||||
});
|
||||
|
||||
describe("SHUTTLE_WILL_ARRIVE_AT_STOP event", () => {
|
||||
test("emits SHUTTLE_WILL_ARRIVE_AT_STOP event before shuttle arrives at a stop", async () => {
|
||||
const { stop1, sampleShuttleNotInRepository: shuttle } = await setupRouteAndOrderedStops();
|
||||
|
||||
const listener = jest.fn();
|
||||
repository.on(ShuttleRepositoryEvent.SHUTTLE_WILL_ARRIVE_AT_STOP, listener);
|
||||
|
||||
shuttle.coordinates = stop1.coordinates;
|
||||
|
||||
const arrivalTime = new Date("2024-01-15T10:30:00Z");
|
||||
await repository.addOrUpdateShuttle(shuttle, arrivalTime.getTime());
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
const emittedPayload = listener.mock.calls[0][0] as any;
|
||||
expect(emittedPayload.willArriveAt).toEqual({
|
||||
shuttleId: shuttle.id,
|
||||
stopId: stop1.id,
|
||||
timestamp: arrivalTime,
|
||||
});
|
||||
});
|
||||
|
||||
test("does not emit event when shuttle is not at a stop", async () => {
|
||||
const { sampleShuttleNotInRepository } = await setupRouteAndOrderedStops();
|
||||
|
||||
const listener = jest.fn();
|
||||
repository.on(ShuttleRepositoryEvent.SHUTTLE_WILL_ARRIVE_AT_STOP, listener);
|
||||
|
||||
const shuttle = { ...sampleShuttleNotInRepository, coordinates: { latitude: 12.5, longitude: 22.5 } }; // Not at any stop
|
||||
|
||||
await repository.addOrUpdateShuttle(shuttle);
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
test("emits multiple events as shuttle visits multiple stops", async () => {
|
||||
const { stop1, stop2, sampleShuttleNotInRepository: shuttle } = await setupRouteAndOrderedStops();
|
||||
|
||||
const listener = jest.fn();
|
||||
repository.on(ShuttleRepositoryEvent.SHUTTLE_WILL_ARRIVE_AT_STOP, listener);
|
||||
|
||||
shuttle.coordinates = stop1.coordinates;
|
||||
|
||||
const firstArrivalTime = new Date("2024-01-15T10:30:00Z");
|
||||
await repository.addOrUpdateShuttle(shuttle, firstArrivalTime.getTime());
|
||||
|
||||
shuttle.coordinates = stop2.coordinates;
|
||||
const secondArrivalTime = new Date("2024-01-15T10:35:00Z");
|
||||
await repository.addOrUpdateShuttle(shuttle, secondArrivalTime.getTime());
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(2);
|
||||
|
||||
const firstPayload = listener.mock.calls[0][0] as any;
|
||||
expect(firstPayload.willArriveAt).toEqual({
|
||||
shuttleId: shuttle.id,
|
||||
stopId: stop1.id,
|
||||
timestamp: firstArrivalTime,
|
||||
});
|
||||
|
||||
const secondPayload = listener.mock.calls[1][0] as any;
|
||||
expect(secondPayload.willArriveAt).toEqual({
|
||||
shuttleId: shuttle.id,
|
||||
stopId: stop2.id,
|
||||
timestamp: secondArrivalTime,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("SHUTTLE_WILL_LEAVE_STOP event", () => {
|
||||
test("emits SHUTTLE_WILL_LEAVE_STOP event when shuttle leaves a stop", async () => {
|
||||
const { stop1, sampleShuttleNotInRepository: shuttle } = await setupRouteAndOrderedStops();
|
||||
shuttle.coordinates = stop1.coordinates;
|
||||
|
||||
const listener = jest.fn();
|
||||
repository.on(ShuttleRepositoryEvent.SHUTTLE_WILL_LEAVE_STOP, listener);
|
||||
|
||||
// Simulate arrival at stop 1
|
||||
const arrivalTime = new Date("2024-01-15T10:30:00Z");
|
||||
await repository.addOrUpdateShuttle(shuttle, arrivalTime.getTime());
|
||||
|
||||
// Test that it actually emits the event correctly and not right after the shuttle arrives
|
||||
await repository.addOrUpdateShuttle(shuttle, arrivalTime.getTime());
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
|
||||
shuttle.coordinates = { latitude: 12.5, longitude: 22.5 }; // Not at any stop
|
||||
|
||||
// Simulate leaving stop 1
|
||||
const leaveTime = new Date("2024-01-15T10:32:00Z");
|
||||
await repository.addOrUpdateShuttle(shuttle, leaveTime.getTime());
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
const emittedPayload = listener.mock.calls[0][0] as any;
|
||||
expect(emittedPayload.stopArrivalThatShuttleIsLeaving).toEqual({
|
||||
shuttleId: shuttle.id,
|
||||
stopId: stop1.id,
|
||||
timestamp: arrivalTime,
|
||||
});
|
||||
});
|
||||
|
||||
test("does not emit event when shuttle was not at a stop", async () => {
|
||||
const { sampleShuttleNotInRepository } = await setupRouteAndOrderedStops();
|
||||
|
||||
const listener = jest.fn();
|
||||
repository.on(ShuttleRepositoryEvent.SHUTTLE_WILL_LEAVE_STOP, listener);
|
||||
|
||||
// Start at coordinates not at any stop
|
||||
const shuttle = { ...sampleShuttleNotInRepository, coordinates: { latitude: 12.5, longitude: 22.5 } };
|
||||
await repository.addOrUpdateShuttle(shuttle);
|
||||
|
||||
// Move to different coordinates; still not at any stop
|
||||
shuttle.coordinates = { latitude: 13.0, longitude: 23.0 };
|
||||
await repository.addOrUpdateShuttle(shuttle);
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
test("emits multiple events as shuttle leaves multiple stops", async () => {
|
||||
const { stop1, stop2, sampleShuttleNotInRepository: shuttle } = await setupRouteAndOrderedStops();
|
||||
|
||||
const listener = jest.fn();
|
||||
repository.on(ShuttleRepositoryEvent.SHUTTLE_WILL_LEAVE_STOP, listener);
|
||||
|
||||
// Arrive at stop1
|
||||
shuttle.coordinates = stop1.coordinates;
|
||||
const firstArrivalTime = new Date("2024-01-15T10:30:00Z");
|
||||
await repository.addOrUpdateShuttle(shuttle, firstArrivalTime.getTime());
|
||||
|
||||
// Leave stop1 and arrive at stop2
|
||||
shuttle.coordinates = stop2.coordinates;
|
||||
const secondArrivalTime = new Date("2024-01-15T10:35:00Z");
|
||||
await repository.addOrUpdateShuttle(shuttle, secondArrivalTime.getTime());
|
||||
|
||||
// Leave stop2
|
||||
shuttle.coordinates = { latitude: 12.5, longitude: 22.5 }; // Not at any stop
|
||||
const secondLeaveTime = new Date("2024-01-15T10:40:00Z");
|
||||
await repository.addOrUpdateShuttle(shuttle, secondLeaveTime.getTime());
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(2);
|
||||
|
||||
const firstPayload = listener.mock.calls[0][0] as any;
|
||||
expect(firstPayload.stopArrivalThatShuttleIsLeaving).toEqual({
|
||||
shuttleId: shuttle.id,
|
||||
stopId: stop1.id,
|
||||
timestamp: firstArrivalTime,
|
||||
});
|
||||
|
||||
const secondPayload = listener.mock.calls[1][0] as any;
|
||||
expect(secondPayload.stopArrivalThatShuttleIsLeaving).toEqual({
|
||||
shuttleId: shuttle.id,
|
||||
stopId: stop2.id,
|
||||
timestamp: secondArrivalTime,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
76
src/repositories/shuttle/eta/BaseInMemoryETARepository.ts
Normal file
76
src/repositories/shuttle/eta/BaseInMemoryETARepository.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { IEta } from "../../../entities/ShuttleRepositoryEntities";
|
||||
import { ETAGetterRepository, ETARepositoryEvent, ETARepositoryEventListener, ETARepositoryEventName } from "./ETAGetterRepository";
|
||||
import EventEmitter from "node:events";
|
||||
|
||||
export abstract class BaseInMemoryETARepository extends EventEmitter implements ETAGetterRepository {
|
||||
protected etas: IEta[] = [];
|
||||
|
||||
async getEtasForShuttleId(shuttleId: string): Promise<IEta[]> {
|
||||
return this.etas.filter(eta => eta.shuttleId === shuttleId);
|
||||
}
|
||||
|
||||
async getEtasForStopId(stopId: string): Promise<IEta[]> {
|
||||
return this.etas.filter(eta => eta.stopId === stopId);
|
||||
}
|
||||
|
||||
async getEtaForShuttleAndStopId(shuttleId: string, stopId: string): Promise<IEta | null> {
|
||||
const eta = this.etas.find(eta => eta.stopId === stopId && eta.shuttleId === shuttleId);
|
||||
return eta ?? null;
|
||||
}
|
||||
|
||||
// Protected setter for internal use
|
||||
protected async addOrUpdateEta(eta: IEta): Promise<void> {
|
||||
const index = this.etas.findIndex((e) => e.stopId === eta.stopId && e.shuttleId === eta.shuttleId);
|
||||
if (index !== -1) {
|
||||
this.etas[index] = eta;
|
||||
} else {
|
||||
this.etas.push(eta);
|
||||
}
|
||||
this.emit(ETARepositoryEvent.ETA_UPDATED, eta);
|
||||
}
|
||||
|
||||
// EventEmitter overrides for type safety
|
||||
override on<T extends ETARepositoryEventName>(
|
||||
event: T,
|
||||
listener: ETARepositoryEventListener<T>,
|
||||
): this;
|
||||
override on(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.on(event, listener);
|
||||
}
|
||||
|
||||
override once<T extends ETARepositoryEventName>(
|
||||
event: T,
|
||||
listener: ETARepositoryEventListener<T>,
|
||||
): this;
|
||||
override once(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.once(event, listener);
|
||||
}
|
||||
|
||||
override off<T extends ETARepositoryEventName>(
|
||||
event: T,
|
||||
listener: ETARepositoryEventListener<T>,
|
||||
): this;
|
||||
override off(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.off(event, listener);
|
||||
}
|
||||
|
||||
override addListener<T extends ETARepositoryEventName>(
|
||||
event: T,
|
||||
listener: ETARepositoryEventListener<T>,
|
||||
): this;
|
||||
override addListener(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.addListener(event, listener);
|
||||
}
|
||||
|
||||
override removeListener<T extends ETARepositoryEventName>(
|
||||
event: T,
|
||||
listener: ETARepositoryEventListener<T>,
|
||||
): this;
|
||||
override removeListener(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.removeListener(event, listener);
|
||||
}
|
||||
|
||||
override removeAllListeners(eventName?: string | symbol): this {
|
||||
return super.removeAllListeners(eventName);
|
||||
}
|
||||
}
|
||||
120
src/repositories/shuttle/eta/BaseRedisETARepository.ts
Normal file
120
src/repositories/shuttle/eta/BaseRedisETARepository.ts
Normal file
@@ -0,0 +1,120 @@
|
||||
import { IEta } from "../../../entities/ShuttleRepositoryEntities";
|
||||
import { BaseRedisRepository } from "../../BaseRedisRepository";
|
||||
import { ETAGetterRepository, ETARepositoryEvent, ETARepositoryEventListener, ETARepositoryEventName } from "./ETAGetterRepository";
|
||||
|
||||
export abstract class BaseRedisETARepository extends BaseRedisRepository implements ETAGetterRepository {
|
||||
private static readonly ETA_KEY_PREFIX = 'shuttle:eta:';
|
||||
|
||||
// Helper methods
|
||||
protected createEtaKey = (shuttleId: string, stopId: string) =>
|
||||
`${BaseRedisETARepository.ETA_KEY_PREFIX}${shuttleId}:${stopId}`;
|
||||
|
||||
createRedisHashFromEta = (eta: IEta): Record<string, string> => ({
|
||||
secondsRemaining: eta.secondsRemaining.toString(),
|
||||
shuttleId: eta.shuttleId,
|
||||
stopId: eta.stopId,
|
||||
systemId: eta.systemId,
|
||||
updatedTime: eta.updatedTime.toISOString(),
|
||||
});
|
||||
|
||||
createEtaFromRedisData = (data: Record<string, string>): IEta => ({
|
||||
secondsRemaining: parseFloat(data.secondsRemaining),
|
||||
shuttleId: data.shuttleId,
|
||||
stopId: data.stopId,
|
||||
systemId: data.systemId,
|
||||
updatedTime: new Date(data.updatedTime),
|
||||
});
|
||||
|
||||
// Getter implementations
|
||||
async getEtasForShuttleId(shuttleId: string): Promise<IEta[]> {
|
||||
const keys = await this.redisClient.keys(`${BaseRedisETARepository.ETA_KEY_PREFIX}${shuttleId}:*`);
|
||||
const etas: IEta[] = [];
|
||||
|
||||
for (const key of keys) {
|
||||
const data = await this.redisClient.hGetAll(key);
|
||||
if (Object.keys(data).length > 0) {
|
||||
etas.push(this.createEtaFromRedisData(data));
|
||||
}
|
||||
}
|
||||
|
||||
return etas;
|
||||
}
|
||||
|
||||
async getEtasForStopId(stopId: string): Promise<IEta[]> {
|
||||
const keys = await this.redisClient.keys(`${BaseRedisETARepository.ETA_KEY_PREFIX}*`);
|
||||
const etas: IEta[] = [];
|
||||
|
||||
for (const key of keys) {
|
||||
const data = await this.redisClient.hGetAll(key);
|
||||
if (Object.keys(data).length > 0 && data.stopId === stopId) {
|
||||
etas.push(this.createEtaFromRedisData(data));
|
||||
}
|
||||
}
|
||||
|
||||
return etas;
|
||||
}
|
||||
|
||||
async getEtaForShuttleAndStopId(shuttleId: string, stopId: string): Promise<IEta | null> {
|
||||
const key = this.createEtaKey(shuttleId, stopId);
|
||||
const data = await this.redisClient.hGetAll(key);
|
||||
|
||||
if (Object.keys(data).length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.createEtaFromRedisData(data);
|
||||
}
|
||||
|
||||
// Protected setter for internal use
|
||||
protected async addOrUpdateEta(eta: IEta): Promise<void> {
|
||||
const key = this.createEtaKey(eta.shuttleId, eta.stopId);
|
||||
const hash = this.createRedisHashFromEta(eta);
|
||||
await this.redisClient.hSet(key, hash);
|
||||
this.emit(ETARepositoryEvent.ETA_UPDATED, eta);
|
||||
}
|
||||
|
||||
// EventEmitter override methods for type safety
|
||||
override on<T extends ETARepositoryEventName>(
|
||||
event: T,
|
||||
listener: ETARepositoryEventListener<T>,
|
||||
): this;
|
||||
override on(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.on(event, listener);
|
||||
}
|
||||
|
||||
override once<T extends ETARepositoryEventName>(
|
||||
event: T,
|
||||
listener: ETARepositoryEventListener<T>,
|
||||
): this;
|
||||
override once(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.once(event, listener);
|
||||
}
|
||||
|
||||
override off<T extends ETARepositoryEventName>(
|
||||
event: T,
|
||||
listener: ETARepositoryEventListener<T>,
|
||||
): this;
|
||||
override off(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.off(event, listener);
|
||||
}
|
||||
|
||||
override addListener<T extends ETARepositoryEventName>(
|
||||
event: T,
|
||||
listener: ETARepositoryEventListener<T>,
|
||||
): this;
|
||||
override addListener(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.addListener(event, listener);
|
||||
}
|
||||
|
||||
override removeListener<T extends ETARepositoryEventName>(
|
||||
event: T,
|
||||
listener: ETARepositoryEventListener<T>,
|
||||
): this;
|
||||
override removeListener(event: string | symbol, listener: (...args: any[]) => void): this {
|
||||
return super.removeListener(event, listener);
|
||||
}
|
||||
|
||||
override removeAllListeners(eventName?: string | symbol): this {
|
||||
return super.removeAllListeners(eventName);
|
||||
}
|
||||
}
|
||||
37
src/repositories/shuttle/eta/ETAGetterRepository.ts
Normal file
37
src/repositories/shuttle/eta/ETAGetterRepository.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { EventEmitter } from "stream";
|
||||
import { IEta } from "../../../entities/ShuttleRepositoryEntities";
|
||||
|
||||
// TODO: Remove these events in ShuttleGetterRepository
|
||||
|
||||
export const ETARepositoryEvent = {
|
||||
ETA_UPDATED: "etaUpdated",
|
||||
ETA_REMOVED: "etaRemoved",
|
||||
ETA_DATA_CLEARED: "etaDataCleared",
|
||||
} as const;
|
||||
|
||||
export type ETARepositoryEventName = typeof ETARepositoryEvent[keyof typeof ETARepositoryEvent];
|
||||
|
||||
export type EtaRemovedEventPayload = IEta;
|
||||
export type EtaDataClearedEventPayload = IEta[];
|
||||
|
||||
export interface ETARepositoryEventPayloads {
|
||||
[ETARepositoryEvent.ETA_UPDATED]: IEta;
|
||||
[ETARepositoryEvent.ETA_REMOVED]: EtaRemovedEventPayload;
|
||||
[ETARepositoryEvent.ETA_DATA_CLEARED]: EtaDataClearedEventPayload;
|
||||
}
|
||||
|
||||
export type ETARepositoryEventListener<T extends ETARepositoryEventName> = (
|
||||
payload: ETARepositoryEventPayloads[T],
|
||||
) => void;
|
||||
|
||||
export interface ETAGetterRepository extends EventEmitter {
|
||||
on<T extends ETARepositoryEventName>(event: T, listener: ETARepositoryEventListener<T>): this;
|
||||
once<T extends ETARepositoryEventName>(event: T, listener: ETARepositoryEventListener<T>): this;
|
||||
off<T extends ETARepositoryEventName>(event: T, listener: ETARepositoryEventListener<T>): this;
|
||||
addListener<T extends ETARepositoryEventName>(event: T, listener: ETARepositoryEventListener<T>): this;
|
||||
removeListener<T extends ETARepositoryEventName>(event: T, listener: ETARepositoryEventListener<T>): this;
|
||||
|
||||
getEtasForShuttleId(shuttleId: string): Promise<IEta[]>;
|
||||
getEtasForStopId(stopId: string): Promise<IEta[]>;
|
||||
getEtaForShuttleAndStopId(shuttleId: string, stopId: string): Promise<IEta | null>;
|
||||
}
|
||||
11
src/repositories/shuttle/eta/ExternalSourceETARepository.ts
Normal file
11
src/repositories/shuttle/eta/ExternalSourceETARepository.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { IEta } from "../../../entities/ShuttleRepositoryEntities";
|
||||
import { ETAGetterRepository } from "./ETAGetterRepository";
|
||||
|
||||
export interface ExternalSourceETARepository extends ETAGetterRepository {
|
||||
/**
|
||||
* Add or update an ETA from an external source (e.g., API or test data).
|
||||
*/
|
||||
addOrUpdateEtaFromExternalSource(eta: IEta): Promise<void>;
|
||||
|
||||
removeEtaIfExists(shuttleId: string, stopId: string): Promise<IEta | null>;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { IEta } from "../../../entities/ShuttleRepositoryEntities";
|
||||
import { ExternalSourceETARepository } from "./ExternalSourceETARepository";
|
||||
import { BaseInMemoryETARepository } from "./BaseInMemoryETARepository";
|
||||
import { ETARepositoryEvent } from "./ETAGetterRepository";
|
||||
|
||||
export class InMemoryExternalSourceETARepository extends BaseInMemoryETARepository implements ExternalSourceETARepository {
|
||||
async addOrUpdateEtaFromExternalSource(eta: IEta): Promise<void> {
|
||||
await this.addOrUpdateEta(eta);
|
||||
}
|
||||
|
||||
async removeEtaIfExists(shuttleId: string, stopId: string): Promise<IEta | null> {
|
||||
const index = this.etas.findIndex((e) => e.stopId === stopId && e.shuttleId === shuttleId);
|
||||
if (index === -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const removedEta = this.etas[index];
|
||||
this.etas.splice(index, 1);
|
||||
this.emit(ETARepositoryEvent.ETA_REMOVED, removedEta);
|
||||
return removedEta;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import { SelfUpdatingETARepository } from "./SelfUpdatingETARepository";
|
||||
import { ShuttleGetterRepository, ShuttleRepositoryEvent, ShuttleStopArrival, ShuttleTravelTimeDataIdentifier, ShuttleTravelTimeDateFilterArguments, ShuttleWillArriveAtStopPayload, ShuttleWillLeaveStopPayload } from "../ShuttleGetterRepository";
|
||||
import { BaseInMemoryETARepository } from "./BaseInMemoryETARepository";
|
||||
import { IOrderedStop, IShuttle } from "../../../entities/ShuttleRepositoryEntities";
|
||||
import { ETARepositoryEvent } from "./ETAGetterRepository";
|
||||
|
||||
export class InMemorySelfUpdatingETARepository extends BaseInMemoryETARepository implements SelfUpdatingETARepository {
|
||||
private referenceTime: Date | null = null;
|
||||
private travelTimeData: Map<string, Array<{ timestamp: number; seconds: number }>> = new Map();
|
||||
|
||||
private isListening = false;
|
||||
|
||||
constructor(
|
||||
readonly shuttleRepository: ShuttleGetterRepository
|
||||
) {
|
||||
super();
|
||||
|
||||
this.setReferenceTime = this.setReferenceTime.bind(this);
|
||||
this.getAverageTravelTimeSeconds = this.getAverageTravelTimeSeconds.bind(this);
|
||||
this.startListeningForUpdates = this.startListeningForUpdates.bind(this);
|
||||
this.handleShuttleWillArriveAtStop = this.handleShuttleWillArriveAtStop.bind(this);
|
||||
this.handleShuttleUpdate = this.handleShuttleUpdate.bind(this);
|
||||
this.updateCascadingEta = this.updateCascadingEta.bind(this);
|
||||
this.getAverageTravelTimeSecondsWithFallbacks = this.getAverageTravelTimeSecondsWithFallbacks.bind(this);
|
||||
this.removeEtaIfExists = this.removeEtaIfExists.bind(this);
|
||||
this.handleShuttleWillLeaveStop = this.handleShuttleWillLeaveStop.bind(this);
|
||||
}
|
||||
|
||||
setReferenceTime(referenceTime: Date): void {
|
||||
this.referenceTime = referenceTime;
|
||||
}
|
||||
|
||||
async getAverageTravelTimeSeconds(
|
||||
{ routeId, fromStopId, toStopId }: ShuttleTravelTimeDataIdentifier,
|
||||
{ from, to }: ShuttleTravelTimeDateFilterArguments
|
||||
): Promise<number | undefined> {
|
||||
const key = `${routeId}:${fromStopId}:${toStopId}`;
|
||||
const dataPoints = this.travelTimeData.get(key);
|
||||
|
||||
if (!dataPoints || dataPoints.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const fromTimestamp = from.getTime();
|
||||
const toTimestamp = to.getTime();
|
||||
|
||||
const filteredPoints = dataPoints.filter(
|
||||
(point) => point.timestamp >= fromTimestamp && point.timestamp <= toTimestamp
|
||||
);
|
||||
|
||||
if (filteredPoints.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const sum = filteredPoints.reduce((acc, point) => acc + point.seconds, 0);
|
||||
return sum / filteredPoints.length;
|
||||
}
|
||||
|
||||
startListeningForUpdates(): void {
|
||||
if (this.isListening) {
|
||||
console.warn("Already listening to updates; did you call startListeningForUpdates twice?");
|
||||
return;
|
||||
}
|
||||
this.shuttleRepository.addListener(ShuttleRepositoryEvent.SHUTTLE_UPDATED, this.handleShuttleUpdate);
|
||||
this.shuttleRepository.addListener(ShuttleRepositoryEvent.SHUTTLE_WILL_ARRIVE_AT_STOP, this.handleShuttleWillArriveAtStop);
|
||||
this.shuttleRepository.addListener(ShuttleRepositoryEvent.SHUTTLE_WILL_LEAVE_STOP, this.handleShuttleWillLeaveStop);
|
||||
this.isListening = true;
|
||||
}
|
||||
stopListeningForUpdates(): void {
|
||||
if (!this.isListening) {
|
||||
return;
|
||||
}
|
||||
this.shuttleRepository.removeListener(ShuttleRepositoryEvent.SHUTTLE_UPDATED, this.handleShuttleUpdate);
|
||||
this.shuttleRepository.removeListener(ShuttleRepositoryEvent.SHUTTLE_WILL_ARRIVE_AT_STOP, this.handleShuttleWillArriveAtStop);
|
||||
this.shuttleRepository.removeListener(ShuttleRepositoryEvent.SHUTTLE_WILL_LEAVE_STOP, this.handleShuttleWillLeaveStop);
|
||||
this.isListening = false;
|
||||
}
|
||||
|
||||
private async getAverageTravelTimeSecondsWithFallbacks(
|
||||
identifier: ShuttleTravelTimeDataIdentifier,
|
||||
dateFilters: ShuttleTravelTimeDateFilterArguments[]
|
||||
): Promise<number | undefined> {
|
||||
for (const dateFilter of dateFilters) {
|
||||
const result = await this.getAverageTravelTimeSeconds(identifier, dateFilter);
|
||||
if (result !== undefined) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private async handleShuttleUpdate(shuttle: IShuttle): Promise<void> {
|
||||
const isAtStop = await this.shuttleRepository.checkIfShuttleIsAtStop(shuttle.id);
|
||||
const lastStop = await this.shuttleRepository.getShuttleLastStopArrival(shuttle.id);
|
||||
if (!lastStop) return;
|
||||
|
||||
if (isAtStop) {
|
||||
// Update the ETA *to* the stop the shuttle is currently at,
|
||||
// before starting from the current stop as normal.
|
||||
// Account for cases where the shuttle arrived way earlier than
|
||||
// expected based on the calculated ETA.
|
||||
|
||||
await this.addOrUpdateEta({
|
||||
secondsRemaining: 1,
|
||||
shuttleId: shuttle.id,
|
||||
stopId: lastStop.stopId,
|
||||
systemId: shuttle.systemId,
|
||||
updatedTime: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
const lastOrderedStop = await this.shuttleRepository.getOrderedStopByRouteAndStopId(shuttle.routeId, lastStop.stopId);
|
||||
|
||||
await this.updateCascadingEta({
|
||||
shuttle,
|
||||
currentStop: lastOrderedStop,
|
||||
originalStopArrival: lastStop,
|
||||
});
|
||||
}
|
||||
|
||||
private async updateCascadingEta({
|
||||
shuttle,
|
||||
currentStop,
|
||||
originalStopArrival,
|
||||
runningTravelTimeSeconds = 0
|
||||
}: {
|
||||
shuttle: IShuttle;
|
||||
currentStop: IOrderedStop | null;
|
||||
originalStopArrival: ShuttleStopArrival;
|
||||
runningTravelTimeSeconds?: number;
|
||||
}) {
|
||||
if (!currentStop) return;
|
||||
const nextStop = currentStop?.nextStop;
|
||||
if (!nextStop) return;
|
||||
// In case the system we have loops around
|
||||
if (nextStop.stopId === originalStopArrival.stopId) return;
|
||||
|
||||
let referenceCurrentTime = new Date();
|
||||
if (this.referenceTime != null) {
|
||||
referenceCurrentTime = this.referenceTime;
|
||||
}
|
||||
|
||||
const oneWeekAgo = new Date(referenceCurrentTime.getTime() - (60 * 60 * 24 * 7 * 1000));
|
||||
const oneDayAgo = new Date(referenceCurrentTime.getTime() - (60 * 60 * 24 * 1000));
|
||||
const twoHoursAgo = new Date(referenceCurrentTime.getTime() - (60 * 60 * 1000));
|
||||
|
||||
const twoHoursInMs = 120 * 60 * 1000;
|
||||
const travelTimeSeconds = await this.getAverageTravelTimeSecondsWithFallbacks({
|
||||
routeId: shuttle.routeId,
|
||||
fromStopId: currentStop.stopId,
|
||||
toStopId: nextStop.stopId,
|
||||
}, [
|
||||
{
|
||||
from: twoHoursAgo,
|
||||
to: new Date(),
|
||||
},
|
||||
{
|
||||
from: new Date(oneDayAgo.getTime() - (twoHoursInMs)),
|
||||
to: oneDayAgo,
|
||||
},
|
||||
{
|
||||
from: new Date(oneWeekAgo.getTime() - (twoHoursInMs)),
|
||||
to: oneWeekAgo,
|
||||
},
|
||||
]);
|
||||
|
||||
if (travelTimeSeconds == undefined) return;
|
||||
|
||||
const elapsedTimeMs = referenceCurrentTime.getTime() - originalStopArrival.timestamp.getTime();
|
||||
const predictedTimeSeconds = travelTimeSeconds - (elapsedTimeMs / 1000) + runningTravelTimeSeconds;
|
||||
|
||||
await this.addOrUpdateEta({
|
||||
secondsRemaining: predictedTimeSeconds,
|
||||
shuttleId: shuttle.id,
|
||||
stopId: nextStop.stopId,
|
||||
systemId: nextStop.systemId,
|
||||
updatedTime: new Date(),
|
||||
});
|
||||
|
||||
const nextStopWithNextNextStop = await this.shuttleRepository.getOrderedStopByRouteAndStopId(shuttle.routeId, nextStop.stopId);
|
||||
await this.updateCascadingEta(
|
||||
{
|
||||
shuttle,
|
||||
currentStop: nextStopWithNextNextStop,
|
||||
originalStopArrival,
|
||||
runningTravelTimeSeconds: runningTravelTimeSeconds + travelTimeSeconds,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private async handleShuttleWillArriveAtStop({
|
||||
lastStopArrival: lastArrival,
|
||||
willArriveAt: currentArrival,
|
||||
}: ShuttleWillArriveAtStopPayload): Promise<void> {
|
||||
if (lastArrival) {
|
||||
// disallow cases where this gets triggered multiple times
|
||||
if (lastArrival.stopId === currentArrival.stopId) return;
|
||||
|
||||
const shuttle = await this.shuttleRepository.getShuttleById(lastArrival.shuttleId);
|
||||
if (!shuttle) return;
|
||||
|
||||
const routeId = shuttle.routeId;
|
||||
const fromStopId = lastArrival.stopId;
|
||||
const toStopId = currentArrival.stopId;
|
||||
|
||||
const travelTimeSeconds = (currentArrival.timestamp.getTime() - lastArrival.timestamp.getTime()) / 1000;
|
||||
await this.addTravelTimeDataPoint({ routeId, fromStopId, toStopId }, travelTimeSeconds, currentArrival.timestamp.getTime());
|
||||
}
|
||||
}
|
||||
|
||||
private async handleShuttleWillLeaveStop({
|
||||
stopArrivalThatShuttleIsLeaving,
|
||||
}: ShuttleWillLeaveStopPayload) {
|
||||
await this.removeEtaIfExists(stopArrivalThatShuttleIsLeaving.shuttleId, stopArrivalThatShuttleIsLeaving.stopId);
|
||||
}
|
||||
|
||||
private async addTravelTimeDataPoint(
|
||||
{ routeId, fromStopId, toStopId }: ShuttleTravelTimeDataIdentifier,
|
||||
travelTimeSeconds: number,
|
||||
timestamp = Date.now(),
|
||||
): Promise<void> {
|
||||
const key = `${routeId}:${fromStopId}:${toStopId}`;
|
||||
const dataPoints = this.travelTimeData.get(key) || [];
|
||||
dataPoints.push({ timestamp, seconds: travelTimeSeconds });
|
||||
this.travelTimeData.set(key, dataPoints);
|
||||
}
|
||||
|
||||
private async removeEtaIfExists(shuttleId: string, stopId: string) {
|
||||
const index = this.etas.findIndex((e) => e.stopId === stopId && e.shuttleId === shuttleId);
|
||||
if (index === -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const removedEta = this.etas[index];
|
||||
this.etas.splice(index, 1);
|
||||
this.emit(ETARepositoryEvent.ETA_REMOVED, removedEta);
|
||||
return removedEta;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { IEta } from "../../../entities/ShuttleRepositoryEntities";
|
||||
import { BaseRedisETARepository } from "./BaseRedisETARepository";
|
||||
import { ExternalSourceETARepository } from "./ExternalSourceETARepository";
|
||||
import { ETARepositoryEvent } from "./ETAGetterRepository";
|
||||
|
||||
export class RedisExternalSourceETARepository extends BaseRedisETARepository implements ExternalSourceETARepository {
|
||||
async addOrUpdateEtaFromExternalSource(eta: IEta): Promise<void> {
|
||||
await this.addOrUpdateEta(eta);
|
||||
}
|
||||
|
||||
async removeEtaIfExists(shuttleId: string, stopId: string): Promise<IEta | null> {
|
||||
const existingEta = await this.getEtaForShuttleAndStopId(shuttleId, stopId);
|
||||
if (existingEta === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const key = this.createEtaKey(shuttleId, stopId);
|
||||
await this.redisClient.del(key);
|
||||
this.emit(ETARepositoryEvent.ETA_REMOVED, existingEta);
|
||||
return existingEta;
|
||||
}
|
||||
}
|
||||
315
src/repositories/shuttle/eta/RedisSelfUpdatingETARepository.ts
Normal file
315
src/repositories/shuttle/eta/RedisSelfUpdatingETARepository.ts
Normal file
@@ -0,0 +1,315 @@
|
||||
import { SelfUpdatingETARepository } from "./SelfUpdatingETARepository";
|
||||
import { BaseRedisETARepository } from "./BaseRedisETARepository";
|
||||
import { RedisClientType } from "redis";
|
||||
import { ShuttleGetterRepository, ShuttleRepositoryEvent, ShuttleStopArrival, ShuttleTravelTimeDataIdentifier, ShuttleTravelTimeDateFilterArguments, ShuttleWillArriveAtStopPayload, ShuttleWillLeaveStopPayload } from "../ShuttleGetterRepository";
|
||||
import { IEta, IOrderedStop, IShuttle } from "../../../entities/ShuttleRepositoryEntities";
|
||||
import { ETARepositoryEvent } from "./ETAGetterRepository";
|
||||
import createRedisClientForRepository from "../../../helpers/createRedisClientForRepository";
|
||||
|
||||
export class RedisSelfUpdatingETARepository extends BaseRedisETARepository implements SelfUpdatingETARepository {
|
||||
private isListening = false;
|
||||
|
||||
constructor(
|
||||
readonly shuttleRepository: ShuttleGetterRepository,
|
||||
redisClient: RedisClientType = createRedisClientForRepository(),
|
||||
private referenceTime: Date | null = null,
|
||||
) {
|
||||
super(redisClient);
|
||||
|
||||
this.setReferenceTime = this.setReferenceTime.bind(this);
|
||||
this.getAverageTravelTimeSeconds = this.getAverageTravelTimeSeconds.bind(this);
|
||||
this.startListeningForUpdates = this.startListeningForUpdates.bind(this);
|
||||
this.handleShuttleWillArriveAtStop = this.handleShuttleWillArriveAtStop.bind(this);
|
||||
this.handleShuttleUpdate = this.handleShuttleUpdate.bind(this);
|
||||
this.updateCascadingEta = this.updateCascadingEta.bind(this);
|
||||
this.getAverageTravelTimeSecondsWithFallbacks = this.getAverageTravelTimeSecondsWithFallbacks.bind(this);
|
||||
this.removeEtaIfExists = this.removeEtaIfExists.bind(this);
|
||||
this.handleShuttleWillLeaveStop = this.handleShuttleWillLeaveStop.bind(this);
|
||||
}
|
||||
|
||||
private createHistoricalEtaTimeSeriesKey = (routeId: string, fromStopId: string, toStopId: string) => {
|
||||
return `shuttle:eta:historical:${routeId}:${fromStopId}:${toStopId}`;
|
||||
}
|
||||
|
||||
setReferenceTime(referenceTime: Date) {
|
||||
this.referenceTime = referenceTime;
|
||||
}
|
||||
|
||||
public async getAverageTravelTimeSeconds(
|
||||
{ routeId, fromStopId, toStopId }: ShuttleTravelTimeDataIdentifier,
|
||||
{ from, to }: ShuttleTravelTimeDateFilterArguments
|
||||
): Promise<number | undefined> {
|
||||
const timeSeriesKey = this.createHistoricalEtaTimeSeriesKey(routeId, fromStopId, toStopId);
|
||||
const fromTimestamp = from.getTime();
|
||||
const toTimestamp = to.getTime();
|
||||
const intervalMs = toTimestamp - fromTimestamp + 1;
|
||||
|
||||
try {
|
||||
const aggregationResult = await this.redisClient.sendCommand([
|
||||
'TS.RANGE',
|
||||
timeSeriesKey,
|
||||
fromTimestamp.toString(),
|
||||
toTimestamp.toString(),
|
||||
'AGGREGATION',
|
||||
'AVG',
|
||||
intervalMs.toString()
|
||||
]) as [string, string][];
|
||||
|
||||
if (aggregationResult && aggregationResult.length > 0) {
|
||||
const [, averageValue] = aggregationResult[0];
|
||||
return parseFloat(averageValue);
|
||||
}
|
||||
|
||||
return;
|
||||
} catch (error) {
|
||||
console.warn(`Failed to get average travel time for ${timeSeriesKey}: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
startListeningForUpdates(): void {
|
||||
if (this.isListening) {
|
||||
console.warn("Already listening to updates; did you call startListeningForUpdates twice?");
|
||||
return;
|
||||
}
|
||||
this.shuttleRepository.addListener(ShuttleRepositoryEvent.SHUTTLE_UPDATED, this.handleShuttleUpdate);
|
||||
this.shuttleRepository.addListener(ShuttleRepositoryEvent.SHUTTLE_WILL_ARRIVE_AT_STOP, this.handleShuttleWillArriveAtStop);
|
||||
this.shuttleRepository.addListener(ShuttleRepositoryEvent.SHUTTLE_WILL_LEAVE_STOP, this.handleShuttleWillLeaveStop);
|
||||
this.isListening = true;
|
||||
}
|
||||
|
||||
stopListeningForUpdates(): void {
|
||||
if (!this.isListening) {
|
||||
return;
|
||||
}
|
||||
this.shuttleRepository.removeListener(ShuttleRepositoryEvent.SHUTTLE_UPDATED, this.handleShuttleUpdate);
|
||||
this.shuttleRepository.removeListener(ShuttleRepositoryEvent.SHUTTLE_WILL_ARRIVE_AT_STOP, this.handleShuttleWillArriveAtStop);
|
||||
this.shuttleRepository.removeListener(ShuttleRepositoryEvent.SHUTTLE_WILL_LEAVE_STOP, this.handleShuttleWillLeaveStop);
|
||||
this.isListening = false;
|
||||
}
|
||||
|
||||
private async getAverageTravelTimeSecondsWithFallbacks(
|
||||
identifier: ShuttleTravelTimeDataIdentifier,
|
||||
dateFilters: ShuttleTravelTimeDateFilterArguments[]
|
||||
): Promise<number | undefined> {
|
||||
for (const dateFilter of dateFilters) {
|
||||
const result = await this.getAverageTravelTimeSeconds(identifier, dateFilter);
|
||||
if (result !== undefined) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private async handleShuttleUpdate(shuttle: IShuttle) {
|
||||
const isAtStop = await this.shuttleRepository.checkIfShuttleIsAtStop(shuttle.id);
|
||||
const lastStop = await this.shuttleRepository.getShuttleLastStopArrival(shuttle.id);
|
||||
if (!lastStop) return;
|
||||
|
||||
if (isAtStop) {
|
||||
// Update the ETA *to* the stop the shuttle is currently at,
|
||||
// before starting from the current stop as normal.
|
||||
// Account for cases where the shuttle arrived way earlier than
|
||||
// expected based on the calculated ETA.
|
||||
|
||||
await this.addOrUpdateEta({
|
||||
secondsRemaining: 1,
|
||||
shuttleId: shuttle.id,
|
||||
stopId: lastStop.stopId,
|
||||
systemId: shuttle.systemId,
|
||||
updatedTime: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
const lastOrderedStop = await this.shuttleRepository.getOrderedStopByRouteAndStopId(shuttle.routeId, lastStop.stopId);
|
||||
|
||||
await this.updateCascadingEta({
|
||||
shuttle,
|
||||
currentStop: lastOrderedStop,
|
||||
originalStopArrival: lastStop,
|
||||
});
|
||||
}
|
||||
|
||||
private async updateCascadingEta({
|
||||
shuttle,
|
||||
currentStop,
|
||||
originalStopArrival,
|
||||
runningTravelTimeSeconds = 0
|
||||
}: {
|
||||
shuttle: IShuttle;
|
||||
currentStop: IOrderedStop | null;
|
||||
originalStopArrival: ShuttleStopArrival;
|
||||
runningTravelTimeSeconds?: number;
|
||||
}) {
|
||||
if (!currentStop) return;
|
||||
const nextStop = currentStop?.nextStop;
|
||||
if (!nextStop) return;
|
||||
// In case the system we have loops around
|
||||
if (nextStop.stopId === originalStopArrival.stopId) return;
|
||||
|
||||
let referenceCurrentTime = new Date();
|
||||
if (this.referenceTime != null) {
|
||||
referenceCurrentTime = this.referenceTime;
|
||||
}
|
||||
|
||||
const oneWeekAgo = new Date(referenceCurrentTime.getTime() - (60 * 60 * 24 * 7 * 1000));
|
||||
const oneDayAgo = new Date(referenceCurrentTime.getTime() - (60 * 60 * 24 * 1000));
|
||||
const twoHoursAgo = new Date(referenceCurrentTime.getTime() - (120 * 60 * 1000));
|
||||
|
||||
const twoHoursInMs = 120 * 60 * 1000;
|
||||
const travelTimeSeconds = await this.getAverageTravelTimeSecondsWithFallbacks({
|
||||
routeId: shuttle.routeId,
|
||||
fromStopId: currentStop.stopId,
|
||||
toStopId: nextStop.stopId,
|
||||
}, [
|
||||
{
|
||||
from: twoHoursAgo,
|
||||
to: new Date(),
|
||||
},
|
||||
{
|
||||
from: new Date(oneDayAgo.getTime() - (twoHoursInMs)),
|
||||
to: oneDayAgo,
|
||||
},
|
||||
{
|
||||
from: new Date(oneWeekAgo.getTime() - (twoHoursInMs)),
|
||||
to: oneWeekAgo,
|
||||
},
|
||||
]);
|
||||
|
||||
if (travelTimeSeconds == undefined) return;
|
||||
|
||||
const elapsedTimeMs = referenceCurrentTime.getTime() - originalStopArrival.timestamp.getTime();
|
||||
const predictedTimeSeconds = travelTimeSeconds - (elapsedTimeMs / 1000) + runningTravelTimeSeconds;
|
||||
|
||||
await this.addOrUpdateEta({
|
||||
secondsRemaining: predictedTimeSeconds,
|
||||
shuttleId: shuttle.id,
|
||||
stopId: nextStop.stopId,
|
||||
systemId: nextStop.systemId,
|
||||
updatedTime: new Date(),
|
||||
});
|
||||
|
||||
const nextStopWithNextNextStop = await this.shuttleRepository.getOrderedStopByRouteAndStopId(shuttle.routeId, nextStop.stopId);
|
||||
await this.updateCascadingEta(
|
||||
{
|
||||
shuttle,
|
||||
currentStop: nextStopWithNextNextStop,
|
||||
originalStopArrival,
|
||||
runningTravelTimeSeconds: runningTravelTimeSeconds + travelTimeSeconds,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
private async handleShuttleWillArriveAtStop({
|
||||
lastStopArrival: lastArrival,
|
||||
willArriveAt: currentArrival,
|
||||
}: ShuttleWillArriveAtStopPayload) {
|
||||
// only update time traveled if last arrival exists
|
||||
if (lastArrival) {
|
||||
// disallow cases where this gets triggered multiple times
|
||||
if (lastArrival.stopId === currentArrival.stopId) return;
|
||||
|
||||
const shuttle = await this.shuttleRepository.getShuttleById(lastArrival.shuttleId);
|
||||
if (!shuttle) return;
|
||||
|
||||
const routeId = shuttle.routeId;
|
||||
const fromStopId = lastArrival.stopId;
|
||||
const toStopId = currentArrival.stopId;
|
||||
|
||||
const travelTimeSeconds = (currentArrival.timestamp.getTime() - lastArrival.timestamp.getTime()) / 1000;
|
||||
await this.addTravelTimeDataPoint({ routeId, fromStopId, toStopId, }, travelTimeSeconds, currentArrival.timestamp.getTime());
|
||||
}
|
||||
}
|
||||
|
||||
private async handleShuttleWillLeaveStop({
|
||||
stopArrivalThatShuttleIsLeaving,
|
||||
}: ShuttleWillLeaveStopPayload) {
|
||||
await this.removeEtaIfExists(stopArrivalThatShuttleIsLeaving.shuttleId, stopArrivalThatShuttleIsLeaving.stopId);
|
||||
}
|
||||
|
||||
|
||||
public async addTravelTimeDataPoint(
|
||||
{ routeId, fromStopId, toStopId }: ShuttleTravelTimeDataIdentifier,
|
||||
travelTimeSeconds: number,
|
||||
timestamp = Date.now(),
|
||||
): Promise<void> {
|
||||
const historicalEtaTimeSeriesKey = this.createHistoricalEtaTimeSeriesKey(routeId, fromStopId, toStopId);
|
||||
|
||||
try {
|
||||
await this.redisClient.sendCommand([
|
||||
'TS.ADD',
|
||||
historicalEtaTimeSeriesKey,
|
||||
timestamp.toString(),
|
||||
travelTimeSeconds.toString(),
|
||||
'LABELS',
|
||||
'routeId',
|
||||
routeId,
|
||||
'fromStopId',
|
||||
fromStopId,
|
||||
'toStopId',
|
||||
toStopId
|
||||
]);
|
||||
} catch (error) {
|
||||
await this.createHistoricalEtaTimeSeriesAndAddDataPoint(
|
||||
historicalEtaTimeSeriesKey,
|
||||
timestamp,
|
||||
travelTimeSeconds,
|
||||
routeId,
|
||||
fromStopId,
|
||||
toStopId
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private async createHistoricalEtaTimeSeriesAndAddDataPoint(
|
||||
timeSeriesKey: string,
|
||||
timestamp: number,
|
||||
travelTimeSeconds: number,
|
||||
routeId: string,
|
||||
fromStopId: string,
|
||||
toStopId: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await this.redisClient.sendCommand([
|
||||
'TS.CREATE',
|
||||
timeSeriesKey,
|
||||
'RETENTION',
|
||||
'2678400000', // one month in milliseconds
|
||||
'LABELS',
|
||||
'routeId',
|
||||
routeId,
|
||||
'fromStopId',
|
||||
fromStopId,
|
||||
'toStopId',
|
||||
toStopId
|
||||
]);
|
||||
await this.redisClient.sendCommand([
|
||||
'TS.ADD',
|
||||
timeSeriesKey,
|
||||
timestamp.toString(),
|
||||
travelTimeSeconds.toString()
|
||||
]);
|
||||
} catch (createError) {
|
||||
await this.redisClient.sendCommand([
|
||||
'TS.ADD',
|
||||
timeSeriesKey,
|
||||
timestamp.toString(),
|
||||
travelTimeSeconds.toString()
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private async removeEtaIfExists(shuttleId: string, stopId: string): Promise<IEta | null> {
|
||||
const existingEta = await this.getEtaForShuttleAndStopId(shuttleId, stopId);
|
||||
if (existingEta === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const key = this.createEtaKey(shuttleId, stopId);
|
||||
await this.redisClient.del(key);
|
||||
this.emit(ETARepositoryEvent.ETA_REMOVED, existingEta);
|
||||
return existingEta;
|
||||
}
|
||||
}
|
||||
28
src/repositories/shuttle/eta/SelfUpdatingETARepository.ts
Normal file
28
src/repositories/shuttle/eta/SelfUpdatingETARepository.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { ShuttleTravelTimeDataIdentifier, ShuttleTravelTimeDateFilterArguments } from "../ShuttleGetterRepository";
|
||||
import { ETAGetterRepository } from "./ETAGetterRepository";
|
||||
|
||||
export interface SelfUpdatingETARepository extends ETAGetterRepository {
|
||||
/**
|
||||
* Attach a event listener to the shuttle repository, listening to
|
||||
* shuttle updates
|
||||
*/
|
||||
startListeningForUpdates(): void;
|
||||
|
||||
/**
|
||||
* Get average travel time between two stops based on historical data.
|
||||
* Returns undefined if no data exists for the specified time range.
|
||||
* @param identifier - The route and stop IDs to query
|
||||
* @param dateFilter - The date range to filter data
|
||||
*/
|
||||
getAverageTravelTimeSeconds(
|
||||
identifier: ShuttleTravelTimeDataIdentifier,
|
||||
dateFilter: ShuttleTravelTimeDateFilterArguments
|
||||
): Promise<number | undefined>;
|
||||
|
||||
/**
|
||||
* Set the "current time" as the class knows it, in order to calculate
|
||||
* ETAs based on past data.
|
||||
* @param referenceTime
|
||||
*/
|
||||
setReferenceTime(referenceTime: Date): void;
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "@jest/globals";
|
||||
import { createClient, RedisClientType } from "redis";
|
||||
import { RepositoryHolder } from "../../../../../testHelpers/RepositoryHolder";
|
||||
import { ExternalSourceETARepository } from "../ExternalSourceETARepository";
|
||||
import { RedisExternalSourceETARepository } from "../RedisExternalSourceETARepository";
|
||||
import { InMemoryExternalSourceETARepository } from "../InMemoryExternalSourceETARepository";
|
||||
import { generateMockEtas } from "../../../../../testHelpers/mockDataGenerators";
|
||||
|
||||
class RedisExternalSourceETARepositoryHolder implements RepositoryHolder<ExternalSourceETARepository> {
|
||||
repo: RedisExternalSourceETARepository | undefined;
|
||||
redisClient: RedisClientType | undefined;
|
||||
|
||||
name = "RedisExternalSourceETARepository"
|
||||
factory = async () => {
|
||||
this.redisClient = createClient({
|
||||
url: process.env.REDIS_URL,
|
||||
});
|
||||
await this.redisClient.connect();
|
||||
this.repo = new RedisExternalSourceETARepository(this.redisClient);
|
||||
return this.repo;
|
||||
}
|
||||
teardown = async () => {
|
||||
if (this.redisClient) {
|
||||
await this.redisClient.flushAll();
|
||||
await this.redisClient.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class InMemoryExternalSourceETARepositoryHolder implements RepositoryHolder<ExternalSourceETARepository> {
|
||||
repo: InMemoryExternalSourceETARepository | undefined;
|
||||
|
||||
name = "InMemoryExternalSourceETARepository"
|
||||
factory = async () => {
|
||||
this.repo = new InMemoryExternalSourceETARepository();
|
||||
return this.repo;
|
||||
}
|
||||
teardown = async () => {
|
||||
// No teardown needed for in-memory
|
||||
}
|
||||
}
|
||||
|
||||
const repositoryImplementations = [
|
||||
new RedisExternalSourceETARepositoryHolder(),
|
||||
new InMemoryExternalSourceETARepositoryHolder()
|
||||
];
|
||||
|
||||
describe.each(repositoryImplementations)('$name', (holder) => {
|
||||
let repository: ExternalSourceETARepository;
|
||||
|
||||
beforeEach(async () => {
|
||||
repository = await holder.factory();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await holder.teardown();
|
||||
});
|
||||
|
||||
describe("addOrUpdateEtaFromExternalSource", () => {
|
||||
test("adds a new ETA if nonexistent", async () => {
|
||||
const mockEtas = generateMockEtas();
|
||||
const newEta = mockEtas[0];
|
||||
|
||||
await repository.addOrUpdateEtaFromExternalSource(newEta);
|
||||
|
||||
const result = await repository.getEtasForShuttleId(newEta.shuttleId);
|
||||
expect(result).toEqual([newEta]);
|
||||
});
|
||||
|
||||
test("updates an existing ETA if it exists", async () => {
|
||||
const mockEtas = generateMockEtas();
|
||||
const existingEta = mockEtas[0];
|
||||
const updatedEta = structuredClone(existingEta);
|
||||
updatedEta.secondsRemaining = existingEta.secondsRemaining + 60;
|
||||
|
||||
await repository.addOrUpdateEtaFromExternalSource(existingEta);
|
||||
await repository.addOrUpdateEtaFromExternalSource(updatedEta);
|
||||
|
||||
const result = await repository.getEtasForShuttleId(existingEta.shuttleId);
|
||||
expect(result).toEqual([updatedEta]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getEtasForShuttleId", () => {
|
||||
test("gets ETAs for a specific shuttle ID", async () => {
|
||||
const mockEtas = generateMockEtas();
|
||||
for (const eta of mockEtas) {
|
||||
await repository.addOrUpdateEtaFromExternalSource(eta);
|
||||
}
|
||||
|
||||
const result = await repository.getEtasForShuttleId("sh1");
|
||||
const expected = mockEtas.filter((eta) => eta.shuttleId === "sh1");
|
||||
expect(result).toHaveLength(expected.length);
|
||||
expect(result).toEqual(expect.arrayContaining(expected));
|
||||
});
|
||||
|
||||
test("returns an empty list if there are no ETAs for the shuttle ID", async () => {
|
||||
const result = await repository.getEtasForShuttleId("nonexistent-shuttle");
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getEtasForStopId", () => {
|
||||
test("gets ETAs for a specific stop ID", async () => {
|
||||
const mockEtas = generateMockEtas();
|
||||
for (const eta of mockEtas) {
|
||||
await repository.addOrUpdateEtaFromExternalSource(eta);
|
||||
}
|
||||
|
||||
const result = await repository.getEtasForStopId("st1");
|
||||
expect(result).toEqual(mockEtas.filter((eta) => eta.stopId === "st1"));
|
||||
});
|
||||
|
||||
test("returns an empty list if there are no ETAs for the stop ID", async () => {
|
||||
const result = await repository.getEtasForStopId("nonexistent-stop");
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getEtaForShuttleAndStopId", () => {
|
||||
test("gets a single ETA for a specific shuttle and stop ID", async () => {
|
||||
const mockEtas = generateMockEtas();
|
||||
const mockEta = mockEtas[0];
|
||||
await repository.addOrUpdateEtaFromExternalSource(mockEta);
|
||||
|
||||
const result = await repository.getEtaForShuttleAndStopId("sh1", "st1");
|
||||
expect(result).toEqual(mockEta);
|
||||
});
|
||||
|
||||
test("returns null if no ETA matches the shuttle and stop ID", async () => {
|
||||
const result = await repository.getEtaForShuttleAndStopId("nonexistent-shuttle", "nonexistent-stop");
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("removeEtaIfExists", () => {
|
||||
test("removes eta given shuttle ID and stop ID", async () => {
|
||||
let mockEtas = generateMockEtas();
|
||||
const stopId = mockEtas[0].stopId;
|
||||
mockEtas = mockEtas.filter((eta) => eta.stopId === stopId);
|
||||
|
||||
await Promise.all(mockEtas.map(async (eta) => {
|
||||
eta.stopId = stopId;
|
||||
await repository.addOrUpdateEtaFromExternalSource(eta);
|
||||
}));
|
||||
|
||||
const etaToRemove = mockEtas[0];
|
||||
await repository.removeEtaIfExists(etaToRemove.shuttleId, etaToRemove.stopId);
|
||||
|
||||
const remainingEtas = await repository.getEtasForStopId(stopId);
|
||||
expect(remainingEtas).toHaveLength(mockEtas.length - 1);
|
||||
});
|
||||
|
||||
test("does nothing if eta doesn't exist", async () => {
|
||||
let mockEtas = generateMockEtas();
|
||||
const stopId = mockEtas[0].stopId;
|
||||
mockEtas = mockEtas.filter((eta) => eta.stopId === stopId);
|
||||
|
||||
await Promise.all(mockEtas.map(async (eta) => {
|
||||
eta.stopId = stopId;
|
||||
await repository.addOrUpdateEtaFromExternalSource(eta);
|
||||
}));
|
||||
|
||||
await repository.removeEtaIfExists("nonexistent-shuttle-id", "nonexistent-stop-id");
|
||||
|
||||
const remainingEtas = await repository.getEtasForStopId(stopId);
|
||||
expect(remainingEtas).toHaveLength(mockEtas.length);
|
||||
});
|
||||
});
|
||||
})
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "@jest/globals";
|
||||
import { createClient, RedisClientType } from "redis";
|
||||
import { RepositoryHolder } from "../../../../../testHelpers/RepositoryHolder";
|
||||
import { SelfUpdatingETARepository } from "../SelfUpdatingETARepository";
|
||||
import { RedisSelfUpdatingETARepository } from "../RedisSelfUpdatingETARepository";
|
||||
import { InMemorySelfUpdatingETARepository } from "../InMemorySelfUpdatingETARepository";
|
||||
import { RedisShuttleRepository } from "../../RedisShuttleRepository";
|
||||
import { UnoptimizedInMemoryShuttleRepository } from "../../UnoptimizedInMemoryShuttleRepository";
|
||||
import { setupRouteAndOrderedStopsForShuttleRepository } from "../../../../../testHelpers/setupRouteAndOrderedStopsForShuttleRepository";
|
||||
import { ShuttleGetterSetterRepository } from "../../ShuttleGetterSetterRepository";
|
||||
import { IShuttle, IStop } from "../../../../entities/ShuttleRepositoryEntities";
|
||||
|
||||
class RedisSelfUpdatingETARepositoryHolder implements RepositoryHolder<SelfUpdatingETARepository> {
|
||||
repo: RedisSelfUpdatingETARepository | undefined;
|
||||
shuttleRepo: RedisShuttleRepository | undefined;
|
||||
redisClient: RedisClientType | undefined;
|
||||
|
||||
name = "RedisSelfUpdatingETARepository"
|
||||
factory = async () => {
|
||||
this.redisClient = createClient({
|
||||
url: process.env.REDIS_URL,
|
||||
});
|
||||
await this.redisClient.connect();
|
||||
await this.redisClient.flushAll();
|
||||
this.shuttleRepo = new RedisShuttleRepository(this.redisClient);
|
||||
this.repo = new RedisSelfUpdatingETARepository(
|
||||
this.shuttleRepo,
|
||||
this.redisClient,
|
||||
);
|
||||
return this.repo;
|
||||
}
|
||||
teardown = async () => {
|
||||
if (this.redisClient) {
|
||||
await this.redisClient.flushAll();
|
||||
await this.redisClient.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class InMemorySelfUpdatingETARepositoryHolder implements RepositoryHolder<SelfUpdatingETARepository> {
|
||||
repo: InMemorySelfUpdatingETARepository | undefined;
|
||||
shuttleRepo: UnoptimizedInMemoryShuttleRepository | undefined;
|
||||
|
||||
name = "InMemorySelfUpdatingETARepository"
|
||||
factory = async () => {
|
||||
this.shuttleRepo = new UnoptimizedInMemoryShuttleRepository();
|
||||
this.repo = new InMemorySelfUpdatingETARepository(this.shuttleRepo);
|
||||
return this.repo;
|
||||
}
|
||||
teardown = async () => {
|
||||
// No teardown needed for in-memory
|
||||
}
|
||||
}
|
||||
|
||||
const repositoryImplementations = [
|
||||
new RedisSelfUpdatingETARepositoryHolder(),
|
||||
new InMemorySelfUpdatingETARepositoryHolder(),
|
||||
];
|
||||
|
||||
describe.each(repositoryImplementations)('$name', (holder) => {
|
||||
let repository: SelfUpdatingETARepository;
|
||||
let shuttleRepository: ShuttleGetterSetterRepository;
|
||||
|
||||
beforeEach(async () => {
|
||||
repository = await holder.factory();
|
||||
shuttleRepository = holder.shuttleRepo!;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await holder.teardown();
|
||||
});
|
||||
|
||||
// Helper function for setting up routes and ordered stops
|
||||
async function setupRouteAndOrderedStops() {
|
||||
return await setupRouteAndOrderedStopsForShuttleRepository(shuttleRepository);
|
||||
}
|
||||
|
||||
async function populateTravelTimeDataForStops({
|
||||
currentTime,
|
||||
shuttle,
|
||||
stop1,
|
||||
stop2,
|
||||
stop3,
|
||||
firstStopArrivalTime = new Date(2025, 0, 1, 11, 0, 0),
|
||||
secondStopArrivalTime = new Date(2025, 0, 1, 11, 15, 0),
|
||||
thirdStopArrivalTime = new Date(2025, 0, 1, 11, 20, 0),
|
||||
}: {
|
||||
currentTime: Date;
|
||||
shuttle: IShuttle;
|
||||
stop1: IStop;
|
||||
stop2: IStop;
|
||||
stop3: IStop;
|
||||
firstStopArrivalTime?: Date;
|
||||
secondStopArrivalTime?: Date;
|
||||
thirdStopArrivalTime?: Date;
|
||||
}) {
|
||||
repository.setReferenceTime(currentTime);
|
||||
repository.startListeningForUpdates();
|
||||
|
||||
shuttle.coordinates = stop1.coordinates;
|
||||
await shuttleRepository.addOrUpdateShuttle(shuttle, firstStopArrivalTime.getTime());
|
||||
|
||||
shuttle.coordinates = stop2.coordinates;
|
||||
await shuttleRepository.addOrUpdateShuttle(shuttle, secondStopArrivalTime.getTime());
|
||||
|
||||
shuttle.coordinates = stop3.coordinates;
|
||||
await shuttleRepository.addOrUpdateShuttle(shuttle, thirdStopArrivalTime.getTime());
|
||||
}
|
||||
|
||||
describe("handleShuttleWillArriveAtStop", () => {
|
||||
test("updates how long the shuttle took to get from one stop to another", async () => {
|
||||
const { route, stop2, stop1, sampleShuttleNotInRepository: shuttle } = await setupRouteAndOrderedStops();
|
||||
|
||||
repository.startListeningForUpdates();
|
||||
|
||||
shuttle.coordinates = stop1.coordinates;
|
||||
|
||||
const firstStopArrivalTime = new Date(2025, 0, 1, 12, 0, 0);
|
||||
await shuttleRepository.addOrUpdateShuttle(shuttle, firstStopArrivalTime.getTime());
|
||||
|
||||
shuttle.coordinates = stop2.coordinates;
|
||||
const secondStopArrivalTime = new Date(2025, 0, 1, 12, 15, 0);
|
||||
await shuttleRepository.addOrUpdateShuttle(shuttle, secondStopArrivalTime.getTime());
|
||||
|
||||
// Necessary to wait for the event emitter subscriber to execute
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
|
||||
const travelTime = await repository.getAverageTravelTimeSeconds({
|
||||
routeId: route.id,
|
||||
fromStopId: stop1.id,
|
||||
toStopId: stop2.id,
|
||||
}, {
|
||||
from: new Date(2025, 0, 1, 11, 0, 0),
|
||||
to: new Date(2025, 0, 1, 13, 0, 0),
|
||||
});
|
||||
expect(travelTime).toEqual(15 * 60);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe("handleShuttleUpdate", () => {
|
||||
async function assertEtaIsValidGivenCurrentTimeAndSecondArrivalTime(
|
||||
currentTime: Date,
|
||||
shuttleSecondArrivalTimeAtFirstStop: Date
|
||||
) {
|
||||
const { stop1, stop2, stop3, sampleShuttleNotInRepository: shuttle } = await setupRouteAndOrderedStops();
|
||||
|
||||
// Populating travel time data
|
||||
await populateTravelTimeDataForStops({ currentTime, shuttle, stop1, stop2, stop3 });
|
||||
|
||||
// Populating ETA data
|
||||
shuttle.coordinates = stop1.coordinates;
|
||||
await shuttleRepository.addOrUpdateShuttle(
|
||||
shuttle,
|
||||
shuttleSecondArrivalTimeAtFirstStop.getTime()
|
||||
);
|
||||
|
||||
shuttle.coordinates = { latitude: 12.5, longitude: 22.5 };
|
||||
await shuttleRepository.addOrUpdateShuttle(
|
||||
shuttle,
|
||||
currentTime.getTime()
|
||||
);
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
|
||||
const secondStopEta = await repository.getEtaForShuttleAndStopId(shuttle.id, stop2.id);
|
||||
expect(secondStopEta?.secondsRemaining).toEqual(8 * 60);
|
||||
|
||||
const thirdStopEta = await repository.getEtaForShuttleAndStopId(shuttle.id, stop3.id);
|
||||
expect(thirdStopEta?.secondsRemaining).toEqual(13 * 60);
|
||||
}
|
||||
|
||||
test("adds ETA entries for stops based on historical data", async () => {
|
||||
const shuttleSecondArrivalTimeAtFirstStop = new Date(2025, 0, 8, 12, 0, 0);
|
||||
const currentTime = new Date(shuttleSecondArrivalTimeAtFirstStop.getTime() + 7 * 60 * 1000);
|
||||
|
||||
await assertEtaIsValidGivenCurrentTimeAndSecondArrivalTime(
|
||||
currentTime, shuttleSecondArrivalTimeAtFirstStop
|
||||
);
|
||||
}, 60000);
|
||||
|
||||
test("uses previous day fallback calculation when no data available from one week ago", async () => {
|
||||
const shuttleSecondArrivalTimeAtFirstStop = new Date(2025, 0, 2, 12, 0, 0);
|
||||
const currentTime = new Date(shuttleSecondArrivalTimeAtFirstStop.getTime() + 7 * 60 * 1000);
|
||||
await assertEtaIsValidGivenCurrentTimeAndSecondArrivalTime(
|
||||
currentTime, shuttleSecondArrivalTimeAtFirstStop
|
||||
);
|
||||
}, 60000);
|
||||
|
||||
test("uses previous two-hour fallback calculation when no data available from one day ago", async () => {
|
||||
const shuttleSecondArrivalTimeAtFirstStop = new Date(2025, 0, 1, 12, 5, 0);
|
||||
const currentTime = new Date(shuttleSecondArrivalTimeAtFirstStop.getTime() + 7 * 60 * 1000);
|
||||
await assertEtaIsValidGivenCurrentTimeAndSecondArrivalTime(
|
||||
currentTime, shuttleSecondArrivalTimeAtFirstStop
|
||||
);
|
||||
});
|
||||
|
||||
test("adds a 'stopgap' entry of 1 second when the shuttle arrives at a stop", async () => {
|
||||
const { stop1, stop2, stop3, sampleShuttleNotInRepository: shuttle } = await setupRouteAndOrderedStops();
|
||||
|
||||
const shuttleSecondArrivalTimeAtFirstStop = new Date(2025, 0, 1, 12, 5, 0);
|
||||
const currentTime = new Date(shuttleSecondArrivalTimeAtFirstStop.getTime() + 7 * 60 * 1000);
|
||||
|
||||
// Populating travel time data
|
||||
await populateTravelTimeDataForStops({ currentTime, shuttle, stop1, stop2, stop3 });
|
||||
|
||||
// Populate ETA data
|
||||
// Simulate shuttle running early for second stop
|
||||
shuttle.coordinates = stop1.coordinates;
|
||||
await shuttleRepository.addOrUpdateShuttle(
|
||||
shuttle,
|
||||
shuttleSecondArrivalTimeAtFirstStop.getTime()
|
||||
);
|
||||
|
||||
shuttle.coordinates = stop2.coordinates;
|
||||
// Call twice to get the ETA repository to read the correct flag
|
||||
await shuttleRepository.addOrUpdateShuttle(
|
||||
shuttle,
|
||||
currentTime.getTime(),
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
|
||||
await shuttleRepository.addOrUpdateShuttle(
|
||||
shuttle,
|
||||
currentTime.getTime(), // ~8 minutes early
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
|
||||
const eta = await repository.getEtaForShuttleAndStopId(shuttle.id, stop2.id);
|
||||
expect(eta?.secondsRemaining).toEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleShuttleWillLeaveStop", () => {
|
||||
test("clears ETA of correct stop on leaving stop", async () => {
|
||||
const { stop1, stop2, stop3, sampleShuttleNotInRepository: shuttle } = await setupRouteAndOrderedStops();
|
||||
|
||||
const shuttleSecondArrivalTimeAtFirstStop = new Date(2025, 0, 8, 12, 0, 0);
|
||||
const shuttleSecondArrivalTimeAtSecondStop = new Date(2025, 0, 8, 12, 15, 0);
|
||||
const currentTime = new Date(shuttleSecondArrivalTimeAtSecondStop.getTime() + 3 * 60 * 1000);
|
||||
|
||||
await populateTravelTimeDataForStops({ currentTime, shuttle, stop1, stop2, stop3 });
|
||||
|
||||
// Populating ETA data
|
||||
shuttle.coordinates = stop1.coordinates;
|
||||
await shuttleRepository.addOrUpdateShuttle(shuttle, shuttleSecondArrivalTimeAtFirstStop.getTime());
|
||||
|
||||
shuttle.coordinates = stop2.coordinates;
|
||||
await shuttleRepository.addOrUpdateShuttle(shuttle, shuttleSecondArrivalTimeAtSecondStop.getTime());
|
||||
|
||||
shuttle.coordinates = { latitude: 12.5, longitude: 12.5 }
|
||||
await shuttleRepository.addOrUpdateShuttle(shuttle, currentTime.getTime());
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
|
||||
const etaForStop3 = await repository.getEtaForShuttleAndStopId(shuttle.id, stop3.id);
|
||||
expect(etaForStop3).not.toBeNull();
|
||||
const etaForStop2 = await repository.getEtaForShuttleAndStopId(shuttle.id, stop2.id);
|
||||
expect(etaForStop2).toBeNull();
|
||||
}, 60000);
|
||||
});
|
||||
|
||||
describe("getAverageTravelTimeSeconds", () => {
|
||||
test("returns the average travel time when historical data exists", async () => {
|
||||
const { route, stop1, stop2, sampleShuttleNotInRepository: shuttle } = await setupRouteAndOrderedStops();
|
||||
|
||||
repository.startListeningForUpdates();
|
||||
|
||||
shuttle.coordinates = stop1.coordinates;
|
||||
|
||||
const firstStopTime = new Date(2025, 0, 1, 12, 0, 0);
|
||||
await shuttleRepository.addOrUpdateShuttle(shuttle, firstStopTime.getTime());
|
||||
|
||||
shuttle.coordinates = stop2.coordinates;
|
||||
const secondStopTime = new Date(2025, 0, 1, 12, 15, 0);
|
||||
await shuttleRepository.addOrUpdateShuttle(shuttle, secondStopTime.getTime());
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
|
||||
const travelTime = await repository.getAverageTravelTimeSeconds({
|
||||
routeId: route.id,
|
||||
fromStopId: stop1.id,
|
||||
toStopId: stop2.id,
|
||||
}, {
|
||||
from: new Date(2025, 0, 1, 11, 0, 0),
|
||||
to: new Date(2025, 0, 1, 13, 0, 0),
|
||||
});
|
||||
|
||||
expect(travelTime).toEqual(15 * 60);
|
||||
});
|
||||
|
||||
test("returns average of multiple data points", async () => {
|
||||
const { route, stop1, stop2, sampleShuttleNotInRepository: shuttle } = await setupRouteAndOrderedStops();
|
||||
|
||||
repository.startListeningForUpdates();
|
||||
|
||||
shuttle.coordinates = stop1.coordinates;
|
||||
|
||||
// First trip: 10 minutes travel time
|
||||
await shuttleRepository.addOrUpdateShuttle(shuttle, new Date(2025, 0, 1, 12, 0, 0).getTime());
|
||||
shuttle.coordinates = stop2.coordinates;
|
||||
await shuttleRepository.addOrUpdateShuttle(shuttle, new Date(2025, 0, 1, 12, 10, 0).getTime());
|
||||
|
||||
// Second trip: 20 minutes travel time
|
||||
shuttle.coordinates = stop1.coordinates;
|
||||
await shuttleRepository.addOrUpdateShuttle(shuttle, new Date(2025, 0, 1, 12, 30, 0).getTime());
|
||||
shuttle.coordinates = stop2.coordinates;
|
||||
await shuttleRepository.addOrUpdateShuttle(shuttle, new Date(2025, 0, 1, 12, 50, 0).getTime());
|
||||
|
||||
const averageTravelTime = await repository.getAverageTravelTimeSeconds({
|
||||
routeId: route.id,
|
||||
fromStopId: stop1.id,
|
||||
toStopId: stop2.id,
|
||||
}, {
|
||||
from: new Date(2025, 0, 1, 11, 0, 0),
|
||||
to: new Date(2025, 0, 1, 14, 0, 0),
|
||||
});
|
||||
|
||||
// Average of 10 minutes and 20 minutes = 15 minutes = 900 seconds
|
||||
expect(averageTravelTime).toBeDefined();
|
||||
});
|
||||
|
||||
test("returns undefined when no data exists", async () => {
|
||||
const { route, stop1, stop2 } = await setupRouteAndOrderedStops();
|
||||
|
||||
repository.startListeningForUpdates();
|
||||
|
||||
const averageTravelTime = await repository.getAverageTravelTimeSeconds({
|
||||
routeId: route.id,
|
||||
fromStopId: stop1.id,
|
||||
toStopId: stop2.id,
|
||||
}, {
|
||||
from: new Date(2025, 0, 1, 11, 0, 0),
|
||||
to: new Date(2025, 0, 1, 14, 0, 0),
|
||||
});
|
||||
|
||||
expect(averageTravelTime).toBeUndefined();
|
||||
});
|
||||
|
||||
test("returns undefined when querying outside the time range of data", async () => {
|
||||
const { route, stop1, stop2, sampleShuttleNotInRepository: shuttle } = await setupRouteAndOrderedStops();
|
||||
|
||||
repository.startListeningForUpdates();
|
||||
|
||||
shuttle.coordinates = stop1.coordinates;
|
||||
|
||||
await shuttleRepository.addOrUpdateShuttle(shuttle, new Date(2025, 0, 1, 12, 0, 0).getTime());
|
||||
shuttle.coordinates = stop2.coordinates;
|
||||
await shuttleRepository.addOrUpdateShuttle(shuttle, new Date(2025, 0, 1, 12, 15, 0).getTime());
|
||||
|
||||
const averageTravelTime = await repository.getAverageTravelTimeSeconds({
|
||||
routeId: route.id,
|
||||
fromStopId: stop1.id,
|
||||
toStopId: stop2.id,
|
||||
}, {
|
||||
from: new Date(2025, 0, 2, 11, 0, 0),
|
||||
to: new Date(2025, 0, 2, 13, 0, 0),
|
||||
});
|
||||
expect(averageTravelTime).toBeUndefined();
|
||||
});
|
||||
});
|
||||
})
|
||||
@@ -4,10 +4,16 @@ import { ServerContext } from "../ServerContext";
|
||||
export const EtaResolvers: Resolvers<ServerContext> = {
|
||||
ETA: {
|
||||
stop: async (parent, args, contextValue, info) => {
|
||||
return await contextValue.repository.getStopById(parent.stopId);
|
||||
const system = contextValue.findSystemById(parent.systemId);
|
||||
if (!system) return null;
|
||||
|
||||
return await system.shuttleRepository.getStopById(parent.stopId);
|
||||
},
|
||||
shuttle: async (parent, args, contextValue, info) => {
|
||||
return await contextValue.repository.getShuttleById(parent.shuttleId);
|
||||
const system = contextValue.findSystemById(parent.systemId);
|
||||
if (!system) return null;
|
||||
|
||||
return await system.shuttleRepository.getShuttleById(parent.shuttleId);
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
94
src/resolvers/MutationResolvers.ts
Normal file
94
src/resolvers/MutationResolvers.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { MutationScheduleNotificationArgs, NotificationResponse, Resolvers } from "../generated/graphql";
|
||||
import { ServerContext } from "../ServerContext";
|
||||
import {
|
||||
ETANotificationScheduler,
|
||||
} from "../notifications/schedulers/ETANotificationScheduler";
|
||||
import { ScheduledNotification } from "../repositories/notifications/NotificationRepository";
|
||||
import { InterchangeSystem } from "../entities/InterchangeSystem";
|
||||
|
||||
async function temp_findMatchingSystemBasedOnShuttleId(context: ServerContext, args: Omit<MutationScheduleNotificationArgs, "input"> & {
|
||||
input: NonNullable<MutationScheduleNotificationArgs["input"]>
|
||||
}) {
|
||||
let matchingSystem: InterchangeSystem | undefined;
|
||||
await Promise.all(context.systems.map(async (system) => {
|
||||
const shuttle = await system.shuttleRepository.getShuttleById(args.input.shuttleId);
|
||||
// Theoretically, there should only be one
|
||||
if (shuttle !== null) {
|
||||
matchingSystem = system;
|
||||
}
|
||||
return shuttle;
|
||||
}));
|
||||
return matchingSystem;
|
||||
}
|
||||
|
||||
export const MutationResolvers: Resolvers<ServerContext> = {
|
||||
// TODO: Require system ID on these endpoints
|
||||
Mutation: {
|
||||
scheduleNotification: async (_parent, args, context, _info) => {
|
||||
let matchingSystem = await temp_findMatchingSystemBasedOnShuttleId(context, args);
|
||||
|
||||
if (!matchingSystem) {
|
||||
return {
|
||||
message: "Shuttle ID doesn't exist",
|
||||
success: false,
|
||||
}
|
||||
}
|
||||
|
||||
const shuttle = await matchingSystem.shuttleRepository.getShuttleById(args.input.shuttleId);
|
||||
if (!shuttle) {
|
||||
return {
|
||||
message: "Shuttle ID doesn't exist",
|
||||
success: false,
|
||||
}
|
||||
}
|
||||
const stop = await matchingSystem.shuttleRepository.getStopById(args.input.stopId);
|
||||
if (!stop) {
|
||||
return {
|
||||
message: "Stop ID doesn't exist",
|
||||
success: false,
|
||||
}
|
||||
}
|
||||
|
||||
const notificationData: ScheduledNotification = {
|
||||
...args.input,
|
||||
secondsThreshold: typeof args.input.secondsThreshold === 'number'
|
||||
? args.input.secondsThreshold
|
||||
: ETANotificationScheduler.defaultSecondsThresholdForNotificationToFire,
|
||||
}
|
||||
|
||||
await matchingSystem.notificationRepository.addOrUpdateNotification(notificationData);
|
||||
|
||||
const response: NotificationResponse = {
|
||||
message: "Notification scheduled",
|
||||
success: true,
|
||||
data: args.input,
|
||||
}
|
||||
return response;
|
||||
},
|
||||
cancelNotification: async (_parent, args, context, _info) => {
|
||||
const matchingSystem = await temp_findMatchingSystemBasedOnShuttleId(context, args);
|
||||
if (!matchingSystem) {
|
||||
return {
|
||||
success: false,
|
||||
message: "Unable to find correct system",
|
||||
data: args.input,
|
||||
}
|
||||
}
|
||||
|
||||
const isScheduled = await matchingSystem.notificationRepository.isNotificationScheduled(args.input)
|
||||
if (isScheduled) {
|
||||
await matchingSystem.notificationRepository.deleteNotificationIfExists(args.input);
|
||||
return {
|
||||
success: true,
|
||||
message: "Notification cancelled",
|
||||
data: args.input,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
message: "Notification doesn't exist"
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -3,50 +3,66 @@ import { ServerContext } from "../ServerContext";
|
||||
|
||||
export const OrderedStopResolvers: Resolvers<ServerContext> = {
|
||||
OrderedStop: {
|
||||
nextStop: async (parent, args, contextValue, info): Promise<OrderedStop | null> => {
|
||||
nextStop: async (parent, args, contextValue, _info): Promise<OrderedStop | null> => {
|
||||
const routeId = parent.routeId;
|
||||
const stopId = parent.stopId;
|
||||
|
||||
const currentOrderedStop = await contextValue.repository.getOrderedStopByRouteAndStopId(routeId, stopId);
|
||||
const system = contextValue.findSystemById(parent.systemId);
|
||||
if (!system) return null;
|
||||
|
||||
const currentOrderedStop = await system.shuttleRepository.getOrderedStopByRouteAndStopId(routeId, stopId);
|
||||
if (!currentOrderedStop) return null;
|
||||
|
||||
const nextOrderedStop = currentOrderedStop.nextStop;
|
||||
if (!nextOrderedStop) return null;
|
||||
|
||||
const nextOrderedStopObject = await contextValue.repository.getStopById(nextOrderedStop.stopId);
|
||||
const nextOrderedStopObject = await system.shuttleRepository.getStopById(nextOrderedStop.stopId);
|
||||
if (!nextOrderedStopObject) return null;
|
||||
|
||||
return {
|
||||
route: parent.route,
|
||||
routeId: parent.routeId,
|
||||
stopId: nextOrderedStopObject.id,
|
||||
systemId: system.id,
|
||||
updatedTime: nextOrderedStopObject.updatedTime
|
||||
}
|
||||
},
|
||||
previousStop: async (parent, args, contextValue, info): Promise<OrderedStop | null> => {
|
||||
previousStop: async (parent, args, contextValue, _info): Promise<OrderedStop | null> => {
|
||||
const routeId = parent.routeId;
|
||||
const stopId = parent.stopId;
|
||||
|
||||
const currentOrderedStop = await contextValue.repository.getOrderedStopByRouteAndStopId(routeId, stopId);
|
||||
const system = contextValue.findSystemById(parent.systemId);
|
||||
if (!system) return null;
|
||||
|
||||
const currentOrderedStop = await system.shuttleRepository.getOrderedStopByRouteAndStopId(routeId, stopId);
|
||||
if (!currentOrderedStop) return null;
|
||||
|
||||
const previousOrderedStop = currentOrderedStop.previousStop;
|
||||
if (!previousOrderedStop) return null;
|
||||
|
||||
const previousOrderedStopObject = await contextValue.repository.getStopById(previousOrderedStop.stopId);
|
||||
const previousOrderedStopObject = await system.shuttleRepository.getStopById(previousOrderedStop.stopId);
|
||||
if (!previousOrderedStopObject) return null;
|
||||
|
||||
return {
|
||||
route: parent.route,
|
||||
routeId: parent.routeId,
|
||||
stopId: previousOrderedStopObject.id,
|
||||
systemId: system.id,
|
||||
updatedTime: previousOrderedStopObject.updatedTime,
|
||||
}
|
||||
},
|
||||
stop: async (parent, args, contextValue, info) => {
|
||||
return await contextValue.repository.getStopById(parent.stopId);
|
||||
stop: async (parent, args, contextValue, _info) => {
|
||||
const system = contextValue.findSystemById(parent.systemId);
|
||||
if (!system) return null;
|
||||
|
||||
return await system.shuttleRepository.getStopById(parent.stopId);
|
||||
},
|
||||
route: async (parent, args, contextValue, info) => {
|
||||
return await contextValue.repository.getRouteById(parent.routeId);
|
||||
route: async (parent, args, contextValue, _info) => {
|
||||
const system = contextValue.findSystemById(parent.systemId);
|
||||
if (!system) return null;
|
||||
|
||||
return await system.shuttleRepository.getRouteById(parent.routeId);
|
||||
},
|
||||
},
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
59
src/resolvers/ParkingStructureResolvers.ts
Normal file
59
src/resolvers/ParkingStructureResolvers.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
import { Resolvers } from "../generated/graphql";
|
||||
import { ServerContext } from "../ServerContext";
|
||||
import { HistoricalParkingAverageFilterArguments } from "../repositories/parking/ParkingGetterRepository";
|
||||
import { GraphQLError } from "graphql/error";
|
||||
import {
|
||||
PARKING_HISTORICAL_AVERAGE_MAXIMUM_TIMESPAN,
|
||||
PARKING_HISTORICAL_AVERAGE_MINIMUM_INTERVAL
|
||||
} from "../environment";
|
||||
|
||||
export const ParkingStructureResolvers: Resolvers<ServerContext> = {
|
||||
ParkingStructure: {
|
||||
historicalAverages: async (parent, args, contextValue, _info) => {
|
||||
/**
|
||||
* @param errorMessage
|
||||
*/
|
||||
function throwBadUserInputError(errorMessage: string) {
|
||||
throw new GraphQLError(errorMessage, {
|
||||
extensions: {
|
||||
code: 'BAD_USER_INPUT',
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const system = contextValue.findSystemById(parent.systemId);
|
||||
|
||||
if (!args.input?.intervalMs) {
|
||||
throwBadUserInputError('No interval provided');
|
||||
return null;
|
||||
}
|
||||
const queryArguments: HistoricalParkingAverageFilterArguments = {
|
||||
from: new Date(args.input.from),
|
||||
intervalMs: args.input.intervalMs,
|
||||
to: new Date(args.input.to),
|
||||
}
|
||||
if (Number.isNaN(queryArguments.from.getTime()
|
||||
|| Number.isNaN(queryArguments.to.getTime()))) {
|
||||
throwBadUserInputError('One or more incorrect dates provided');
|
||||
}
|
||||
if (queryArguments.from.getTime() > queryArguments.to.getTime()) {
|
||||
throwBadUserInputError("`from` date can't be greater than the `to` date");
|
||||
}
|
||||
|
||||
// Limit queries for improved performance
|
||||
if (queryArguments.to.getTime() - queryArguments.from.getTime() > PARKING_HISTORICAL_AVERAGE_MAXIMUM_TIMESPAN) {
|
||||
throwBadUserInputError('Maximum timespan exceeded');
|
||||
}
|
||||
if (queryArguments.intervalMs < PARKING_HISTORICAL_AVERAGE_MINIMUM_INTERVAL) {
|
||||
throwBadUserInputError('Provided interval is less than minimum interval');
|
||||
}
|
||||
|
||||
const parkingAverages = await system?.parkingRepository?.getHistoricalAveragesOfParkingStructureCounts(parent.id, queryArguments);
|
||||
if (!parkingAverages) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return parkingAverages;
|
||||
}
|
||||
}
|
||||
}
|
||||
42
src/resolvers/ParkingSystemResolvers.ts
Normal file
42
src/resolvers/ParkingSystemResolvers.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { Resolvers } from "../generated/graphql";
|
||||
import { ServerContext } from "../ServerContext";
|
||||
|
||||
export const ParkingSystemResolvers: Resolvers<ServerContext> = {
|
||||
ParkingSystem: {
|
||||
parkingStructures: async (parent, _args, contextValue, _info) => {
|
||||
const system = contextValue.findSystemById(parent.systemId);
|
||||
if (!system) {
|
||||
return [];
|
||||
}
|
||||
const parkingRepository = system.parkingRepository;
|
||||
if (!parkingRepository) return [];
|
||||
|
||||
const parkingStructures = await parkingRepository.getParkingStructures();
|
||||
return parkingStructures
|
||||
.slice()
|
||||
.sort((a, b) => a.name.localeCompare(b.name))
|
||||
.map((structure) => {
|
||||
return {
|
||||
...structure,
|
||||
systemId: parent.systemId
|
||||
};
|
||||
});
|
||||
},
|
||||
parkingStructure: async (parent, args, contextValue, _info) => {
|
||||
if (!args.id) return null;
|
||||
|
||||
const system = contextValue.findSystemById(parent.systemId);
|
||||
if (!system) {
|
||||
return null;
|
||||
}
|
||||
const parkingRepository = system.parkingRepository;
|
||||
if (!parkingRepository) return null;
|
||||
|
||||
const parkingStructure = await parkingRepository.getParkingStructureById(args.id);
|
||||
return parkingStructure ? {
|
||||
...parkingStructure,
|
||||
systemId: parent.systemId,
|
||||
} : null;
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,62 @@
|
||||
import { ServerContext } from "../ServerContext";
|
||||
import { Resolvers } from "../generated/graphql";
|
||||
|
||||
const GRAPHQL_SCHEMA_MIN_VERSION = 1;
|
||||
const GRAPHQL_SCHEMA_CURRENT_VERSION = 1;
|
||||
|
||||
export const QueryResolvers: Resolvers<ServerContext> = {
|
||||
Query: {
|
||||
systems: async (parent, args, contextValue, info) => {
|
||||
return await contextValue.repository.getSystems();
|
||||
systems: async (_parent, args, contextValue, _info) => {
|
||||
return contextValue.systems
|
||||
.slice()
|
||||
.sort((a, b) => a.name.localeCompare(b.name))
|
||||
.map((system) => {
|
||||
return {
|
||||
name: system.name,
|
||||
id: system.id,
|
||||
};
|
||||
})
|
||||
},
|
||||
system: async (parent, args, contextValue, info) => {
|
||||
system: async (_parent, args, contextValue, _info) => {
|
||||
if (!args.id) return null;
|
||||
const system = await contextValue.repository.getSystemById(args.id);
|
||||
const system = contextValue.findSystemById(args.id);
|
||||
if (system === null) return null;
|
||||
|
||||
return {
|
||||
name: system.name,
|
||||
id: system.id,
|
||||
};
|
||||
}
|
||||
},
|
||||
// TODO: Update the GraphQL schema to require a system ID
|
||||
isNotificationScheduled: async (_parent, args, contextValue, _info) => {
|
||||
const notificationData = args.input;
|
||||
|
||||
for (let system of contextValue.systems) {
|
||||
const isScheduled = await system.notificationRepository.isNotificationScheduled(notificationData);
|
||||
if (isScheduled) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
secondsThresholdForNotification: async (_parent, args, contextValue, _info) => {
|
||||
const notificationData = args.input;
|
||||
|
||||
for (let system of contextValue.systems) {
|
||||
const isScheduled = await system.notificationRepository.isNotificationScheduled(notificationData);
|
||||
if (isScheduled) {
|
||||
return await system.notificationRepository.getSecondsThresholdForNotificationIfExists(args.input);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
schemaMinVersion: async (_parent, _args, _contextValue, _info) => {
|
||||
return GRAPHQL_SCHEMA_MIN_VERSION;
|
||||
},
|
||||
schemaCurrentVersion: async (_parent, _args, _contextValue, _info) => {
|
||||
return GRAPHQL_SCHEMA_CURRENT_VERSION;
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,34 +3,67 @@ import { ServerContext } from "../ServerContext";
|
||||
|
||||
export const RouteResolvers: Resolvers<ServerContext> = {
|
||||
Route: {
|
||||
shuttles: async (parent, args, contextValue, info) => {
|
||||
const shuttles = await contextValue.repository.getShuttlesByRouteId(parent.id);
|
||||
shuttles: async (parent, args, contextValue, _info) => {
|
||||
const system = contextValue.findSystemById(parent.systemId);
|
||||
if (!system) return null;
|
||||
|
||||
return shuttles.map(({
|
||||
const shuttles = await system.shuttleRepository.getShuttlesByRouteId(parent.id);
|
||||
|
||||
return shuttles
|
||||
.slice()
|
||||
.sort((a, b) => a.name.localeCompare(b.name))
|
||||
.map(({
|
||||
coordinates,
|
||||
name,
|
||||
id,
|
||||
orientationInDegrees,
|
||||
updatedTime
|
||||
}) => ({
|
||||
coordinates: coordinates as Coordinates,
|
||||
name,
|
||||
route: parent,
|
||||
routeId: parent.id,
|
||||
id,
|
||||
orientationInDegrees,
|
||||
systemId: parent.systemId,
|
||||
updatedTime,
|
||||
}));
|
||||
},
|
||||
orderedStop: async (parent, args, contextValue, info) => {
|
||||
orderedStop: async (parent, args, contextValue, _info) => {
|
||||
if (!args.forStopId) return null;
|
||||
const orderedStop = await contextValue.repository.getOrderedStopByRouteAndStopId(parent.id, args.forStopId);
|
||||
|
||||
const system = contextValue.findSystemById(parent.systemId);
|
||||
if (!system) return null;
|
||||
|
||||
const orderedStop = await system.shuttleRepository.getOrderedStopByRouteAndStopId(parent.id, args.forStopId);
|
||||
if (!orderedStop) return null;
|
||||
|
||||
const stop = await contextValue.repository.getStopById(orderedStop.stopId);
|
||||
const stop = await system.shuttleRepository.getStopById(orderedStop.stopId);
|
||||
if (!stop) return null;
|
||||
|
||||
return {
|
||||
stopId: args.forStopId,
|
||||
routeId: parent.id,
|
||||
route: parent,
|
||||
systemId: system.id,
|
||||
updatedTime: orderedStop.updatedTime,
|
||||
}
|
||||
},
|
||||
orderedStops: async (parent, args, contextValue, _info) => {
|
||||
const system = contextValue.findSystemById(parent.systemId);
|
||||
if (!system) return null;
|
||||
|
||||
const orderedStops = await system.shuttleRepository.getOrderedStopsByRouteId(parent.id);
|
||||
return orderedStops
|
||||
.slice()
|
||||
.sort((a, b) => a.position - b.position)
|
||||
.map(({ routeId, stopId, position, systemId, updatedTime }) => ({
|
||||
routeId,
|
||||
stopId,
|
||||
position,
|
||||
systemId,
|
||||
updatedTime,
|
||||
}));
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,9 +3,13 @@ import { ServerContext } from "../ServerContext";
|
||||
|
||||
export const ShuttleResolvers: Resolvers<ServerContext> = {
|
||||
Shuttle: {
|
||||
eta: async (parent, args, contextValue, info) => {
|
||||
eta: async (parent, args, contextValue, _) => {
|
||||
if (!args.forStopId) return null;
|
||||
const etaForStopId = await contextValue.repository.getEtaForShuttleAndStopId(parent.id, args.forStopId);
|
||||
|
||||
const system = contextValue.findSystemById(parent.systemId);
|
||||
if (!system) return null;
|
||||
|
||||
const etaForStopId = await system.etaRepository.getEtaForShuttleAndStopId(parent.id, args.forStopId);
|
||||
if (etaForStopId === null) return null;
|
||||
|
||||
return {
|
||||
@@ -13,32 +17,46 @@ export const ShuttleResolvers: Resolvers<ServerContext> = {
|
||||
secondsRemaining: etaForStopId.secondsRemaining,
|
||||
shuttleId: parent.id,
|
||||
shuttle: parent,
|
||||
systemId: system.id,
|
||||
updatedTimeMs: etaForStopId.updatedTime,
|
||||
};
|
||||
},
|
||||
etas: async (parent, args, contextValue, info) => {
|
||||
const etasForShuttle = await contextValue.repository.getEtasForShuttleId(parent.id);
|
||||
etas: async (parent, args, contextValue, _) => {
|
||||
const system = contextValue.findSystemById(parent.systemId);
|
||||
if (!system) return null;
|
||||
|
||||
const etasForShuttle = await system.etaRepository.getEtasForShuttleId(parent.id);
|
||||
if (!etasForShuttle) return null;
|
||||
|
||||
const computedEtas = await Promise.all(etasForShuttle.map(async ({
|
||||
secondsRemaining,
|
||||
stopId,
|
||||
}): Promise<Eta | null> => {
|
||||
return {
|
||||
const computedEtas = await Promise.all(
|
||||
etasForShuttle.map(async ({
|
||||
secondsRemaining,
|
||||
stopId,
|
||||
shuttle: parent,
|
||||
shuttleId: parent.id,
|
||||
}
|
||||
updatedTime
|
||||
}): Promise<Eta | null> => {
|
||||
return {
|
||||
secondsRemaining,
|
||||
stopId,
|
||||
shuttle: parent,
|
||||
shuttleId: parent.id,
|
||||
systemId: system.id,
|
||||
updatedTime: updatedTime,
|
||||
}
|
||||
}));
|
||||
|
||||
if (computedEtas.every((eta) => eta !== null)) {
|
||||
return computedEtas;
|
||||
return computedEtas
|
||||
.slice()
|
||||
.sort((a, b) => (a!.secondsRemaining - b!.secondsRemaining));
|
||||
}
|
||||
|
||||
return [];
|
||||
},
|
||||
route: async (parent, args, contextValue, info) => {
|
||||
const route = await contextValue.repository.getRouteById(parent.routeId);
|
||||
route: async (parent, args, contextValue, _) => {
|
||||
const system = contextValue.findSystemById(parent.systemId);
|
||||
if (!system) return null;
|
||||
|
||||
const route = await system.shuttleRepository.getRouteById(parent.routeId);
|
||||
if (route === null) return null;
|
||||
|
||||
return {
|
||||
@@ -46,7 +64,9 @@ export const ShuttleResolvers: Resolvers<ServerContext> = {
|
||||
id: route.id,
|
||||
name: route.name,
|
||||
polylineCoordinates: route.polylineCoordinates,
|
||||
systemId: system.id,
|
||||
updatedTimeMs: route.updatedTime
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,11 +3,21 @@ import { ServerContext } from "../ServerContext";
|
||||
|
||||
export const StopResolvers: Resolvers<ServerContext> = {
|
||||
Stop: {
|
||||
orderedStops: async (parent, args, contextValue, info) => {
|
||||
return await contextValue.repository.getOrderedStopsByStopId(parent.id);
|
||||
orderedStops: async (parent, args, contextValue, _info) => {
|
||||
const system = contextValue.findSystemById(parent.systemId);
|
||||
if (!system) {
|
||||
return [];
|
||||
}
|
||||
const orderedStops = await system.shuttleRepository.getOrderedStopsByStopId(parent.id);
|
||||
return orderedStops.slice().sort((a, b) => a.position - b.position);
|
||||
},
|
||||
etas: async (parent, args, contextValue, info) => {
|
||||
return await contextValue.repository.getEtasForStopId(parent.id);
|
||||
etas: async (parent, args, contextValue, _info) => {
|
||||
const system = contextValue.findSystemById(parent.systemId);
|
||||
if (!system) {
|
||||
return [];
|
||||
}
|
||||
const etas = await system.etaRepository.getEtasForStopId(parent.id);
|
||||
return etas.slice().sort((a, b) => a.secondsRemaining - b.secondsRemaining);
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,15 +3,32 @@ import { ServerContext } from "../ServerContext";
|
||||
|
||||
export const SystemResolvers: Resolvers<ServerContext> = {
|
||||
System: {
|
||||
routes: async (parent, args, contextValue, info) => {
|
||||
return await contextValue.repository.getRoutesBySystemId(parent.id);
|
||||
routes: async (parent, _args, contextValue, _info) => {
|
||||
const system = contextValue.findSystemById(parent.id);
|
||||
if (!system) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const routes = await system.shuttleRepository.getRoutes();
|
||||
return routes.slice().sort((a, b) => a.name.localeCompare(b.name));
|
||||
},
|
||||
stops: async (parent, args, contextValue, info) => {
|
||||
return await contextValue.repository.getStopsBySystemId(parent.id);
|
||||
stops: async (parent, _args, contextValue, _info) => {
|
||||
const system = contextValue.findSystemById(parent.id);
|
||||
if (!system) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const stops = await system.shuttleRepository.getStops();
|
||||
return stops.slice().sort((a, b) => a.name.localeCompare(b.name));
|
||||
},
|
||||
stop: async (parent, args, contextValue, info) => {
|
||||
stop: async (parent, args, contextValue, _info) => {
|
||||
if (!args.id) return null;
|
||||
const stop = await contextValue.repository.getStopById(args.id);
|
||||
const system = contextValue.findSystemById(parent.id);
|
||||
if (!system) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const stop = await system.shuttleRepository.getStopById(args.id);
|
||||
if (stop === null) return null;
|
||||
|
||||
if (stop.systemId !== parent.id) return null;
|
||||
@@ -20,11 +37,17 @@ export const SystemResolvers: Resolvers<ServerContext> = {
|
||||
id: stop.id,
|
||||
name: stop.name,
|
||||
coordinates: stop.coordinates as Coordinates,
|
||||
systemId: parent.id,
|
||||
updatedTimeMs: stop.updatedTime,
|
||||
};
|
||||
},
|
||||
route: async (parent, args, contextValue, info) => {
|
||||
route: async (parent, args, contextValue, _info) => {
|
||||
if (!args.id) return null;
|
||||
const route = await contextValue.repository.getRouteById(args.id);
|
||||
const system = contextValue.findSystemById(parent.id);
|
||||
if (!system) {
|
||||
return null;
|
||||
}
|
||||
const route = await system.shuttleRepository.getRouteById(args.id);
|
||||
if (route === null) return null;
|
||||
|
||||
if (route.systemId !== parent.id) return null;
|
||||
@@ -34,19 +57,43 @@ export const SystemResolvers: Resolvers<ServerContext> = {
|
||||
id: route.id,
|
||||
name: route.name,
|
||||
polylineCoordinates: route.polylineCoordinates as Coordinates[],
|
||||
systemId: parent.id,
|
||||
updatedTimeMs: route.updatedTime,
|
||||
};
|
||||
},
|
||||
shuttle: async (parent, args, contextValue, info) => {
|
||||
shuttle: async (parent, args, contextValue, _info) => {
|
||||
if (!args.id) return null;
|
||||
const shuttle = await contextValue.repository.getShuttleById(args.id);
|
||||
const system = contextValue.findSystemById(parent.id);
|
||||
if (!system) {
|
||||
return null;
|
||||
}
|
||||
const shuttle = await system.shuttleRepository.getShuttleById(args.id);
|
||||
if (shuttle === null) return null;
|
||||
|
||||
if (shuttle.systemId !== parent.id) return null;
|
||||
|
||||
return shuttle;
|
||||
},
|
||||
shuttles: async (parent, args, contextValue, info) => {
|
||||
return await contextValue.repository.getShuttlesBySystemId(parent.id);
|
||||
}
|
||||
shuttles: async (parent, _args, contextValue, _info) => {
|
||||
const system = contextValue.findSystemById(parent.id);
|
||||
if (!system) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const shuttles = await system.shuttleRepository.getShuttles();
|
||||
return shuttles.slice().sort((a, b) => a.name.localeCompare(b.name));
|
||||
},
|
||||
parkingSystem: async (parent, _args, contextValue, _info) => {
|
||||
const system = contextValue.findSystemById(parent.id);
|
||||
if (!system) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!system.parkingRepository) return null;
|
||||
|
||||
return {
|
||||
systemId: parent.id,
|
||||
};
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,41 +1,39 @@
|
||||
import { beforeEach, describe, expect, it } from "@jest/globals";
|
||||
import { setupTestServerContext } from "../testHelpers/apolloTestServerHelpers";
|
||||
import { IEta, IShuttle, IStop, ISystem } from "../../src/entities/entities";
|
||||
import { setupTestServerContext, setupTestServerHolder } from "../../../testHelpers/apolloTestServerHelpers";
|
||||
import { IEta, IShuttle, IStop } from "../../entities/ShuttleRepositoryEntities";
|
||||
import {
|
||||
addMockEtaToRepository, addMockShuttleToRepository,
|
||||
addMockEtaToRepository,
|
||||
addMockShuttleToRepository,
|
||||
addMockStopToRepository,
|
||||
addMockSystemToRepository
|
||||
} from "../testHelpers/repositorySetupHelpers";
|
||||
import assert = require("node:assert");
|
||||
} from "../../../testHelpers/repositorySetupHelpers";
|
||||
import { ExternalSourceETARepository } from "../../repositories/shuttle/eta/ExternalSourceETARepository";
|
||||
import assert from "node:assert";
|
||||
|
||||
describe("EtaResolvers", () => {
|
||||
const holder = setupTestServerHolder();
|
||||
const context = setupTestServerContext();
|
||||
|
||||
let mockSystem: ISystem;
|
||||
let mockShuttle: IShuttle;
|
||||
let mockStop: IStop;
|
||||
let expectedEta: IEta;
|
||||
|
||||
beforeEach(async () => {
|
||||
mockSystem = await addMockSystemToRepository(context.repository);
|
||||
mockShuttle = await addMockShuttleToRepository(context.repository, mockSystem.id);
|
||||
mockStop = await addMockStopToRepository(context.repository, mockSystem.id);
|
||||
expectedEta = await addMockEtaToRepository(context.repository, mockStop.id, mockShuttle.id);
|
||||
mockShuttle = await addMockShuttleToRepository(context.systems[0].shuttleRepository, context.systems[0].id);
|
||||
mockStop = await addMockStopToRepository(context.systems[0].shuttleRepository, context.systems[0].id);
|
||||
expectedEta = await addMockEtaToRepository(context.systems[0].etaRepository as ExternalSourceETARepository, mockStop.id, mockShuttle.id);
|
||||
});
|
||||
|
||||
async function getResponseForEtaQuery(query: string) {
|
||||
const response = await context.testServer.executeOperation({
|
||||
return await holder.testServer.executeOperation({
|
||||
query,
|
||||
variables: {
|
||||
systemId: mockSystem.id,
|
||||
systemId: context.systems[0].id,
|
||||
shuttleId: mockShuttle.id,
|
||||
},
|
||||
}, {
|
||||
contextValue: {
|
||||
repository: context.repository,
|
||||
}
|
||||
contextValue: context
|
||||
|
||||
});
|
||||
return response;
|
||||
}
|
||||
|
||||
describe("stop", () => {
|
||||
@@ -87,4 +85,4 @@ describe("EtaResolvers", () => {
|
||||
expect(eta.shuttle.id).toEqual(expectedEta.shuttleId);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
187
src/resolvers/__tests__/MutationResolverTests.test.ts
Normal file
187
src/resolvers/__tests__/MutationResolverTests.test.ts
Normal file
@@ -0,0 +1,187 @@
|
||||
import { describe, expect, it } from "@jest/globals";
|
||||
import { setupTestServerContext, setupTestServerHolder } from "../../../testHelpers/apolloTestServerHelpers";
|
||||
import {
|
||||
addMockShuttleToRepository,
|
||||
addMockStopToRepository,
|
||||
} from "../../../testHelpers/repositorySetupHelpers";
|
||||
import assert = require("node:assert");
|
||||
import { NotificationInput } from "../../generated/graphql";
|
||||
|
||||
describe("MutationResolvers", () => {
|
||||
const holder = setupTestServerHolder()
|
||||
const context = setupTestServerContext();
|
||||
|
||||
async function getServerResponse(query: string, notificationInput: { deviceId: string; shuttleId: string; stopId: string }) {
|
||||
return await holder.testServer.executeOperation({
|
||||
query,
|
||||
variables: {
|
||||
input: notificationInput,
|
||||
}
|
||||
}, {
|
||||
contextValue: context
|
||||
});
|
||||
}
|
||||
|
||||
describe("scheduleNotification", () => {
|
||||
const query = `
|
||||
mutation ScheduleNotification($input: NotificationInput!) {
|
||||
scheduleNotification(input: $input) {
|
||||
success
|
||||
message
|
||||
data {
|
||||
deviceId
|
||||
shuttleId
|
||||
stopId
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
async function assertFailedResponse(response: any, notificationInput: NotificationInput) {
|
||||
assert(response.body.kind === "single");
|
||||
expect(response.body.singleResult.errors).toBeUndefined();
|
||||
const notificationResponse = response.body.singleResult.data?.scheduleNotification as any;
|
||||
expect(notificationResponse.success).toBe(false);
|
||||
|
||||
expect(await context.systems[0].notificationRepository.isNotificationScheduled(notificationInput)).toBe(false);
|
||||
}
|
||||
|
||||
|
||||
it("adds a notification to the notification service", async () => {
|
||||
const system = context.systems[0];
|
||||
const shuttle = await addMockShuttleToRepository(context.systems[0].shuttleRepository, system.id);
|
||||
const stop = await addMockStopToRepository(context.systems[0].shuttleRepository, system.id);
|
||||
|
||||
const notificationInput = {
|
||||
deviceId: "1",
|
||||
shuttleId: shuttle.id,
|
||||
stopId: stop.id,
|
||||
secondsThreshold: 240,
|
||||
};
|
||||
const response = await getServerResponse(query, notificationInput);
|
||||
|
||||
assert(response.body.kind === "single");
|
||||
expect(response.body.singleResult.errors).toBeUndefined();
|
||||
|
||||
const expectedNotificationData: any = {
|
||||
...notificationInput,
|
||||
}
|
||||
delete expectedNotificationData.secondsThreshold;
|
||||
const notificationResponse = response.body.singleResult.data?.scheduleNotification as any;
|
||||
expect(notificationResponse?.success).toBe(true);
|
||||
expect(notificationResponse?.data).toEqual(expectedNotificationData);
|
||||
|
||||
expect(await context.systems[0].notificationRepository.getSecondsThresholdForNotificationIfExists(expectedNotificationData)).toBe(240);
|
||||
});
|
||||
|
||||
it("adds a notification with the default seconds threshold if none is provided", async () => {
|
||||
const system = context.systems[0];
|
||||
const shuttle = await addMockShuttleToRepository(context.systems[0].shuttleRepository, system.id);
|
||||
const stop = await addMockStopToRepository(context.systems[0].shuttleRepository, system.id);
|
||||
|
||||
const notificationInput = {
|
||||
deviceId: "1",
|
||||
shuttleId: shuttle.id,
|
||||
stopId: stop.id,
|
||||
};
|
||||
const response = await getServerResponse(query, notificationInput);
|
||||
|
||||
assert(response.body.kind === "single");
|
||||
expect(response.body.singleResult.errors).toBeUndefined();
|
||||
|
||||
const notificationResponse = response.body.singleResult.data?.scheduleNotification as any;
|
||||
expect(notificationResponse?.success).toBe(true);
|
||||
|
||||
expect(await context.systems[0].notificationRepository.getSecondsThresholdForNotificationIfExists(notificationInput)).toBe(180);
|
||||
});
|
||||
|
||||
it("fails if the shuttle ID doesn't exist", async () => {
|
||||
const system = context.systems[0];
|
||||
const stop = await addMockStopToRepository(context.systems[0].shuttleRepository, system.id);
|
||||
|
||||
const notificationInput = {
|
||||
deviceId: "1",
|
||||
shuttleId: "1",
|
||||
stopId: stop.id,
|
||||
}
|
||||
const response = await getServerResponse(query, notificationInput);
|
||||
await assertFailedResponse(response, notificationInput);
|
||||
});
|
||||
|
||||
it("fails if the stop ID doesn't exist", async () => {
|
||||
const system = context.systems[0];
|
||||
const shuttle = await addMockShuttleToRepository(context.systems[0].shuttleRepository, system.id);
|
||||
|
||||
const notificationInput = {
|
||||
deviceId: "1",
|
||||
shuttleId: shuttle.id,
|
||||
stopId: "1",
|
||||
}
|
||||
const response = await getServerResponse(query, notificationInput);
|
||||
|
||||
await assertFailedResponse(response, notificationInput);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cancelNotification", () => {
|
||||
const query = `
|
||||
mutation CancelNotification($input: NotificationInput!) {
|
||||
cancelNotification(input: $input) {
|
||||
success
|
||||
message
|
||||
data {
|
||||
deviceId
|
||||
shuttleId
|
||||
stopId
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
it("removes the notification from the notification service", async () => {
|
||||
const system = context.systems[0];
|
||||
const shuttle = await addMockShuttleToRepository(context.systems[0].shuttleRepository, system.id);
|
||||
const stop = await addMockStopToRepository(context.systems[0].shuttleRepository, system.id);
|
||||
|
||||
const notificationInput: any = {
|
||||
deviceId: "1",
|
||||
shuttleId: shuttle.id,
|
||||
stopId: stop.id,
|
||||
secondsThreshold: 180,
|
||||
}
|
||||
await context.systems[0].notificationRepository.addOrUpdateNotification(notificationInput);
|
||||
|
||||
const notificationLookup = {
|
||||
...notificationInput
|
||||
}
|
||||
delete notificationLookup.secondsThreshold;
|
||||
|
||||
const response = await getServerResponse(query, notificationLookup);
|
||||
|
||||
assert(response.body.kind === "single");
|
||||
expect(response.body.singleResult.errors).toBeUndefined();
|
||||
|
||||
const notificationResponse = response.body.singleResult.data?.cancelNotification as any;
|
||||
expect(notificationResponse.success).toBe(true);
|
||||
expect(notificationResponse.data).toEqual(notificationLookup);
|
||||
|
||||
expect(await context.systems[0].notificationRepository.isNotificationScheduled(notificationLookup)).toBe(false);
|
||||
});
|
||||
|
||||
it("fails if the notification doesn't exist", async () => {
|
||||
const notificationInput = {
|
||||
deviceId: "1",
|
||||
shuttleId: "1",
|
||||
stopId: "1",
|
||||
}
|
||||
|
||||
const response = await getServerResponse(query, notificationInput);
|
||||
|
||||
assert(response.body.kind === "single");
|
||||
expect(response.body.singleResult.errors).toBeUndefined();
|
||||
|
||||
const notificationResponse = response.body.singleResult.data?.cancelNotification as any;
|
||||
expect(notificationResponse.success).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,25 +1,24 @@
|
||||
import { beforeEach, describe, expect, it } from "@jest/globals";
|
||||
import { setupTestServerContext } from "../testHelpers/apolloTestServerHelpers";
|
||||
import { IRoute, IStop, ISystem } from "../../src/entities/entities";
|
||||
import { generateMockOrderedStops, generateMockStops } from "../testHelpers/mockDataGenerators";
|
||||
import { addMockRouteToRepository, addMockSystemToRepository } from "../testHelpers/repositorySetupHelpers";
|
||||
import { setupTestServerContext, setupTestServerHolder } from "../../../testHelpers/apolloTestServerHelpers";
|
||||
import { IRoute, IStop } from "../../entities/ShuttleRepositoryEntities";
|
||||
import { generateMockOrderedStops, generateMockStops } from "../../../testHelpers/mockDataGenerators";
|
||||
import { addMockRouteToRepository } from "../../../testHelpers/repositorySetupHelpers";
|
||||
import assert = require("node:assert");
|
||||
|
||||
describe("OrderedStopResolvers", () => {
|
||||
const holder = setupTestServerHolder();
|
||||
const context = setupTestServerContext();
|
||||
|
||||
let mockSystem: ISystem;
|
||||
let mockRoute: IRoute;
|
||||
let mockStops: IStop[];
|
||||
|
||||
beforeEach(async () => {
|
||||
mockSystem = await addMockSystemToRepository(context.repository);
|
||||
mockRoute = await addMockRouteToRepository(context.repository, mockSystem.id);
|
||||
mockRoute = await addMockRouteToRepository(context.systems[0].shuttleRepository, context.systems[0].id);
|
||||
|
||||
mockStops = generateMockStops();
|
||||
await Promise.all(mockStops.map(async (mockStop) => {
|
||||
mockStop.systemId = mockSystem.id;
|
||||
await context.repository.addOrUpdateStop(mockStop);
|
||||
mockStop.systemId = context.systems[0].id;
|
||||
await context.systems[0].shuttleRepository.addOrUpdateStop(mockStop);
|
||||
}));
|
||||
});
|
||||
|
||||
@@ -37,8 +36,8 @@ describe("OrderedStopResolvers", () => {
|
||||
// Link the stops together
|
||||
orderedStops[0].nextStop = orderedStops[1];
|
||||
orderedStops[1].previousStop = orderedStops[0];
|
||||
await context.repository.addOrUpdateOrderedStop(orderedStops[0]);
|
||||
await context.repository.addOrUpdateOrderedStop(orderedStops[1]);
|
||||
await context.systems[0].shuttleRepository.addOrUpdateOrderedStop(orderedStops[0]);
|
||||
await context.systems[0].shuttleRepository.addOrUpdateOrderedStop(orderedStops[1]);
|
||||
return orderedStops;
|
||||
}
|
||||
|
||||
@@ -59,17 +58,16 @@ describe("OrderedStopResolvers", () => {
|
||||
}
|
||||
`;
|
||||
|
||||
return await context.testServer.executeOperation({
|
||||
return await holder.testServer.executeOperation({
|
||||
query,
|
||||
variables: {
|
||||
systemId: mockSystem.id,
|
||||
systemId: context.systems[0].id,
|
||||
routeId: mockRoute.id,
|
||||
stopId,
|
||||
},
|
||||
}, {
|
||||
contextValue: {
|
||||
repository: context.repository,
|
||||
}
|
||||
contextValue: context
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
@@ -93,7 +91,7 @@ describe("OrderedStopResolvers", () => {
|
||||
it("returns null if there is no next stop in the repository", async () => {
|
||||
const orderedStops = await setUpOrderedStopsInRepository();
|
||||
orderedStops[0].nextStop = undefined;
|
||||
await context.repository.addOrUpdateOrderedStop(orderedStops[0]);
|
||||
await context.systems[0].shuttleRepository.addOrUpdateOrderedStop(orderedStops[0]);
|
||||
|
||||
const response = await getResponseForNextStopQuery(orderedStops[0].stopId);
|
||||
|
||||
@@ -104,7 +102,7 @@ describe("OrderedStopResolvers", () => {
|
||||
|
||||
it("returns null if the next stop object no longer exists", async () => {
|
||||
const orderedStops = await setUpOrderedStopsInRepository();
|
||||
await context.repository.removeStopIfExists(orderedStops[1].stopId);
|
||||
await context.systems[0].shuttleRepository.removeStopIfExists(orderedStops[1].stopId);
|
||||
|
||||
const response = await getResponseForNextStopQuery(orderedStops[0].stopId);
|
||||
|
||||
@@ -131,17 +129,16 @@ describe("OrderedStopResolvers", () => {
|
||||
}
|
||||
`;
|
||||
|
||||
return await context.testServer.executeOperation({
|
||||
return await holder.testServer.executeOperation({
|
||||
query,
|
||||
variables: {
|
||||
systemId: mockSystem.id,
|
||||
systemId: context.systems[0].id,
|
||||
routeId: mockRoute.id,
|
||||
stopId,
|
||||
},
|
||||
}, {
|
||||
contextValue: {
|
||||
repository: context.repository,
|
||||
}
|
||||
contextValue: context
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
@@ -164,7 +161,7 @@ describe("OrderedStopResolvers", () => {
|
||||
it("returns null if there is no previous stop in the repository", async () => {
|
||||
const orderedStops = await setUpOrderedStopsInRepository();
|
||||
orderedStops[1].previousStop = undefined;
|
||||
await context.repository.addOrUpdateOrderedStop(orderedStops[1]);
|
||||
await context.systems[0].shuttleRepository.addOrUpdateOrderedStop(orderedStops[1]);
|
||||
|
||||
const response = await getResponseForPreviousStopQuery(orderedStops[1].stopId);
|
||||
|
||||
@@ -175,7 +172,7 @@ describe("OrderedStopResolvers", () => {
|
||||
|
||||
it("returns null if the current stop no longer exists", async () => {
|
||||
const orderedStops = await setUpOrderedStopsInRepository();
|
||||
await context.repository.removeStopIfExists(orderedStops[0].stopId);
|
||||
await context.systems[0].shuttleRepository.removeStopIfExists(orderedStops[0].stopId);
|
||||
|
||||
const response = await getResponseForPreviousStopQuery(orderedStops[1].stopId);
|
||||
|
||||
@@ -206,16 +203,15 @@ describe("OrderedStopResolvers", () => {
|
||||
}
|
||||
`;
|
||||
|
||||
return await context.testServer.executeOperation({
|
||||
return await holder.testServer.executeOperation({
|
||||
query,
|
||||
variables: {
|
||||
systemId: mockSystem.id,
|
||||
systemId: context.systems[0].id,
|
||||
stopId,
|
||||
}
|
||||
}, {
|
||||
contextValue: {
|
||||
repository: context.repository,
|
||||
}
|
||||
contextValue: context
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
@@ -225,7 +221,7 @@ describe("OrderedStopResolvers", () => {
|
||||
orderedStops[0].stopId = mockStops[0].id;
|
||||
|
||||
// Add one stop only
|
||||
await context.repository.addOrUpdateOrderedStop(orderedStops[0]);
|
||||
await context.systems[0].shuttleRepository.addOrUpdateOrderedStop(orderedStops[0]);
|
||||
|
||||
const response = await getResponseForRouteQuery(orderedStops[1].stopId);
|
||||
|
||||
@@ -256,24 +252,23 @@ describe("OrderedStopResolvers", () => {
|
||||
}
|
||||
`;
|
||||
|
||||
return await context.testServer.executeOperation({
|
||||
return await holder.testServer.executeOperation({
|
||||
query,
|
||||
variables: {
|
||||
systemId: mockSystem.id,
|
||||
systemId: context.systems[0].id,
|
||||
routeId: mockRoute.id,
|
||||
stopId,
|
||||
}
|
||||
}, {
|
||||
contextValue: {
|
||||
repository: context.repository,
|
||||
}
|
||||
contextValue: context
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
it("returns the associated stop if it exists", async () => {
|
||||
const orderedStops = await setUpOrderedStopsInRepository();
|
||||
orderedStops[0].stopId = mockStops[0].id;
|
||||
await context.repository.addOrUpdateOrderedStop(orderedStops[0]);
|
||||
await context.systems[0].shuttleRepository.addOrUpdateOrderedStop(orderedStops[0]);
|
||||
|
||||
const response = await getResponseForStopQuery(orderedStops[0].stopId);
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
|
||||
import { setupTestServerContext, setupTestServerHolder } from "../../../testHelpers/apolloTestServerHelpers";
|
||||
import { InterchangeSystem } from "../../entities/InterchangeSystem";
|
||||
import { generateParkingStructures } from "../../../testHelpers/mockDataGenerators";
|
||||
import { HistoricalParkingAverageQueryInput } from "../../generated/graphql";
|
||||
import assert = require("node:assert");
|
||||
|
||||
jest.mock("../../environment");
|
||||
|
||||
describe("ParkingStructureResolver", () => {
|
||||
const holder = setupTestServerHolder();
|
||||
const context = setupTestServerContext();
|
||||
|
||||
let mockSystem: InterchangeSystem;
|
||||
|
||||
beforeEach(async () => {
|
||||
mockSystem = context.systems[0];
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
describe("historicalAverages", () => {
|
||||
const query = `
|
||||
query GetParkingStructureHistoricalAverages(
|
||||
$systemId: ID!,
|
||||
$parkingStructureId: ID!,
|
||||
$historicalAverageInput: HistoricalParkingAverageQueryInput!
|
||||
) {
|
||||
system(id: $systemId) {
|
||||
parkingSystem {
|
||||
parkingStructure(id: $parkingStructureId) {
|
||||
historicalAverages(input: $historicalAverageInput) {
|
||||
from
|
||||
to
|
||||
averageSpotsAvailable
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
it("gets data for historical averages", async () => {
|
||||
jest.useFakeTimers();
|
||||
jest.setSystemTime(new Date());
|
||||
|
||||
const parkingStructure = generateParkingStructures()[0];
|
||||
parkingStructure.spotsAvailable = parkingStructure.capacity;
|
||||
mockSystem.parkingRepository?.setLoggingInterval(100);
|
||||
|
||||
// Simulate repeated updates
|
||||
for (let i = 0; i < 6; i += 1) {
|
||||
jest.setSystemTime(new Date(Date.now() + 1000));
|
||||
parkingStructure.spotsAvailable = parkingStructure.spotsAvailable - 100;
|
||||
await mockSystem.parkingRepository?.addOrUpdateParkingStructure(parkingStructure);
|
||||
}
|
||||
|
||||
const historicalAverageInput: HistoricalParkingAverageQueryInput = {
|
||||
from: new Date(Date.now() - 5000).getTime(),
|
||||
intervalMs: 2000,
|
||||
to: new Date().getTime(),
|
||||
};
|
||||
const response = await holder.testServer.executeOperation({
|
||||
query,
|
||||
variables: {
|
||||
systemId: mockSystem.id,
|
||||
parkingStructureId: parkingStructure.id,
|
||||
historicalAverageInput,
|
||||
},
|
||||
}, {
|
||||
contextValue: context,
|
||||
});
|
||||
|
||||
assert(response.body.kind === 'single');
|
||||
expect(response.body.singleResult.errors).toBeUndefined();
|
||||
const historicalAverages = (response.body.singleResult.data as any).system.parkingSystem.parkingStructure.historicalAverages;
|
||||
expect(historicalAverages).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
});
|
||||
200
src/resolvers/__tests__/ParkingSystemResolverTests.test.ts
Normal file
200
src/resolvers/__tests__/ParkingSystemResolverTests.test.ts
Normal file
@@ -0,0 +1,200 @@
|
||||
import { beforeEach, describe, expect, it } from "@jest/globals";
|
||||
import { generateParkingStructures } from "../../../testHelpers/mockDataGenerators";
|
||||
import { setupTestServerContext, setupTestServerHolder } from "../../../testHelpers/apolloTestServerHelpers";
|
||||
import { InterchangeSystem } from "../../entities/InterchangeSystem";
|
||||
import assert = require("node:assert");
|
||||
|
||||
|
||||
describe("ParkingSystemResolver", () => {
|
||||
const holder = setupTestServerHolder();
|
||||
const context = setupTestServerContext();
|
||||
|
||||
let mockSystem: InterchangeSystem;
|
||||
|
||||
beforeEach(async () => {
|
||||
mockSystem = context.systems[0];
|
||||
});
|
||||
|
||||
async function getResponseFromQueryNeedingSystemId(query: string) {
|
||||
return await holder.testServer.executeOperation({
|
||||
query,
|
||||
variables: {
|
||||
systemId: mockSystem.id,
|
||||
},
|
||||
}, {
|
||||
contextValue: context,
|
||||
});
|
||||
}
|
||||
|
||||
describe("parkingStructures", () => {
|
||||
const query = `
|
||||
query GetParkingStructuresBySystem($systemId: ID!) {
|
||||
system(id: $systemId) {
|
||||
parkingSystem {
|
||||
parkingStructures {
|
||||
name
|
||||
id
|
||||
capacity
|
||||
spotsAvailable
|
||||
coordinates {
|
||||
latitude
|
||||
longitude
|
||||
}
|
||||
address
|
||||
updatedTime
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
it("gets parking structures associated with the system id", async () => {
|
||||
let expectedParkingStructures = generateParkingStructures();
|
||||
await Promise.all(expectedParkingStructures.map(async (structure) => {
|
||||
await context.systems[0].parkingRepository?.addOrUpdateParkingStructure(structure);
|
||||
}));
|
||||
|
||||
// Dates are transformed into epoch timestamps when serialized
|
||||
expectedParkingStructures = expectedParkingStructures.map((structure) => {
|
||||
const newStructure = { ...structure };
|
||||
// @ts-ignore
|
||||
newStructure.updatedTime = newStructure.updatedTime.getTime();
|
||||
return newStructure;
|
||||
});
|
||||
|
||||
const response = await getResponseFromQueryNeedingSystemId(query);
|
||||
|
||||
assert(response.body.kind === "single");
|
||||
expect(response.body.singleResult.errors).toBeUndefined();
|
||||
|
||||
const parkingStructures = (response.body.singleResult.data as any).system.parkingSystem.parkingStructures;
|
||||
expect(parkingStructures).toEqual(expectedParkingStructures);
|
||||
});
|
||||
|
||||
it("returns a blank array if there are no parking structures", async () => {
|
||||
const response = await getResponseFromQueryNeedingSystemId(query);
|
||||
|
||||
assert(response.body.kind === "single");
|
||||
expect(response.body.singleResult.errors).toBeUndefined();
|
||||
|
||||
const parkingStructures = (response.body.singleResult.data as any).system.parkingSystem.parkingStructures;
|
||||
|
||||
expect(parkingStructures).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("returns parking structures sorted by name", async () => {
|
||||
// Create two out-of-order structures by name
|
||||
const s1 = {
|
||||
id: "ps1",
|
||||
name: "Barrera",
|
||||
capacity: 100,
|
||||
spotsAvailable: 50,
|
||||
coordinates: { latitude: 0, longitude: 0 },
|
||||
address: "1 Anywhere",
|
||||
updatedTime: new Date(),
|
||||
};
|
||||
const s2 = {
|
||||
id: "ps2",
|
||||
name: "Anderson",
|
||||
capacity: 100,
|
||||
spotsAvailable: 50,
|
||||
coordinates: { latitude: 0, longitude: 0 },
|
||||
address: "2 Anywhere",
|
||||
updatedTime: new Date(),
|
||||
};
|
||||
await context.systems[0].parkingRepository?.addOrUpdateParkingStructure(s1);
|
||||
await context.systems[0].parkingRepository?.addOrUpdateParkingStructure(s2);
|
||||
|
||||
const minimalQuery = `
|
||||
query GetParkingStructuresBySystem($systemId: ID!) {
|
||||
system(id: $systemId) {
|
||||
parkingSystem {
|
||||
parkingStructures {
|
||||
name
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await getResponseFromQueryNeedingSystemId(minimalQuery);
|
||||
|
||||
assert(response.body.kind === "single");
|
||||
expect(response.body.singleResult.errors).toBeUndefined();
|
||||
const names = (response.body.singleResult.data as any).system.parkingSystem.parkingStructures.map((p: any) => p.name);
|
||||
expect(names).toEqual([s2.name, s1.name]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("parkingStructure", () => {
|
||||
async function getResponseForParkingStructureQuery(parkingStructureId: string) {
|
||||
const query = `
|
||||
query GetParkingStructureBySystem($systemId: ID!, $parkingStructureId: ID!) {
|
||||
system(id: $systemId) {
|
||||
parkingSystem {
|
||||
parkingStructure(id: $parkingStructureId) {
|
||||
name
|
||||
id
|
||||
capacity
|
||||
spotsAvailable
|
||||
coordinates {
|
||||
latitude
|
||||
longitude
|
||||
}
|
||||
address
|
||||
updatedTime
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
return await holder.testServer.executeOperation({
|
||||
query,
|
||||
variables: {
|
||||
systemId: mockSystem.id,
|
||||
parkingStructureId,
|
||||
}
|
||||
}, {
|
||||
contextValue: context
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
it("returns the correct parking structure given the id", async () => {
|
||||
const generatedParkingStructures = generateParkingStructures();
|
||||
await Promise.all(generatedParkingStructures.map(async (structure) => {
|
||||
await context.systems[0].parkingRepository?.addOrUpdateParkingStructure(structure);
|
||||
}));
|
||||
const expectedParkingStructure = generatedParkingStructures[1];
|
||||
// @ts-ignore
|
||||
expectedParkingStructure.updatedTime = expectedParkingStructure.updatedTime.getTime();
|
||||
|
||||
const response = await getResponseForParkingStructureQuery(expectedParkingStructure.id);
|
||||
|
||||
assert(response.body.kind === "single");
|
||||
expect(response.body.singleResult.errors).toBeUndefined();
|
||||
|
||||
const parkingStructure = (response.body.singleResult.data as any).system.parkingSystem.parkingStructure;
|
||||
expect(parkingStructure).toEqual(expectedParkingStructure);
|
||||
});
|
||||
|
||||
it("returns null if there is no matching parking structure", async () => {
|
||||
const generatedParkingStructures = generateParkingStructures();
|
||||
await Promise.all(generatedParkingStructures.map(async (structure) => {
|
||||
await context.systems[0].parkingRepository?.addOrUpdateParkingStructure(structure);
|
||||
}));
|
||||
|
||||
const nonexistentId = generatedParkingStructures[0].id + "12345";
|
||||
|
||||
const response = await getResponseForParkingStructureQuery(nonexistentId);
|
||||
|
||||
assert(response.body.kind === "single");
|
||||
expect(response.body.singleResult.errors).toBeUndefined();
|
||||
|
||||
const parkingStructure = (response.body.singleResult.data as any).system.parkingSystem.parkingStructure;
|
||||
expect(parkingStructure).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user