Skip to content

Commit f6ff259

Browse files
committed
refactor: [torrust#297] new error checks and refactoring
Date converter helper function now throws errors if the timestamp passed as argument is not an integer and if the Date() constructor returns an invalid date.
1 parent f26a2e3 commit f6ff259

File tree

2 files changed

+26
-9
lines changed

2 files changed

+26
-9
lines changed

components/torrent/TorrentCreationDateTab.vue

+1-4
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,7 @@
1414
<template v-if="!collapsed">
1515
<div class="flex flex-col w-full h-full p-6 grow bg-base-100 rounded-2xl">
1616
<template v-if="torrent.creation_date">
17-
<!--<Markdown :source="torrent.name" />-->
18-
{{ creationDateUTC }}
17+
{{ unixTimeToHumanReadableUTC(torrent.creation_date) }}
1918
</template>
2019
<template v-else>
2120
<span class="italic text-neutral-content">No creation date provided.</span>
@@ -42,8 +41,6 @@ const props = defineProps({
4241
}
4342
});
4443
45-
const creationDateUTC = unixTimeToHumanReadableUTC(props.torrent.creation_date);
46-
4744
</script>
4845

4946
<style scoped>

src/helpers/DateConverter.ts

+25-5
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,34 @@
11
type UnixTime = number;
22

3-
function isValidDate (date: Date) {
4-
return date instanceof Date && !isNaN(date.valueOf());
5-
}
3+
class InvalidDateError extends Error {}
64

75
// Takes the date in seconds from Epoch time and converts it to human readable format.
86

9-
export function unixTimeToHumanReadableUTC (seconds: UnixTime) {
7+
export function unixTimeToHumanReadableUTC (creationDate: UnixTime) {
8+
try {
9+
return dateFromSeconds(creationDate);
10+
} catch (error) {
11+
return ("Invalid date");
12+
}
13+
}
14+
15+
function dateFromSeconds (seconds: number) {
16+
if (!validateTimestamp(seconds))
17+
{ throw new TypeError("Torrent creation date is not an integer"); }
18+
1019
const milliseconds = seconds * 1000;
1120
const convertedDate = new Date(milliseconds);
1221

13-
return isValidDate(convertedDate) ? convertedDate.toDateString() : "Invalid date";
22+
if (!validateDate(convertedDate))
23+
{ throw new InvalidDateError("Date is not valid"); }
24+
25+
return convertedDate.toDateString();
26+
}
27+
28+
function validateDate (date: Date) {
29+
return date instanceof Date && !isNaN(date.valueOf());
30+
}
31+
32+
function validateTimestamp (timestamp: UnixTime) {
33+
return Number.isInteger(timestamp);
1434
}

0 commit comments

Comments
 (0)