Skip to content

Commit

Permalink
refactor: [torrust#297] new error checks and refactoring
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mario-nt committed Nov 29, 2023
1 parent f26a2e3 commit f6ff259
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
5 changes: 1 addition & 4 deletions components/torrent/TorrentCreationDateTab.vue
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@
<template v-if="!collapsed">
<div class="flex flex-col w-full h-full p-6 grow bg-base-100 rounded-2xl">
<template v-if="torrent.creation_date">
<!--<Markdown :source="torrent.name" />-->
{{ creationDateUTC }}
{{ unixTimeToHumanReadableUTC(torrent.creation_date) }}
</template>
<template v-else>
<span class="italic text-neutral-content">No creation date provided.</span>
Expand All @@ -42,8 +41,6 @@ const props = defineProps({
}
});
const creationDateUTC = unixTimeToHumanReadableUTC(props.torrent.creation_date);
</script>

<style scoped>
Expand Down
30 changes: 25 additions & 5 deletions src/helpers/DateConverter.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,34 @@
type UnixTime = number;

function isValidDate (date: Date) {
return date instanceof Date && !isNaN(date.valueOf());
}
class InvalidDateError extends Error {}

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

export function unixTimeToHumanReadableUTC (seconds: UnixTime) {
export function unixTimeToHumanReadableUTC (creationDate: UnixTime) {
try {
return dateFromSeconds(creationDate);
} catch (error) {
return ("Invalid date");
}
}

function dateFromSeconds (seconds: number) {
if (!validateTimestamp(seconds))
{ throw new TypeError("Torrent creation date is not an integer"); }

const milliseconds = seconds * 1000;
const convertedDate = new Date(milliseconds);

return isValidDate(convertedDate) ? convertedDate.toDateString() : "Invalid date";
if (!validateDate(convertedDate))
{ throw new InvalidDateError("Date is not valid"); }

return convertedDate.toDateString();
}

function validateDate (date: Date) {
return date instanceof Date && !isNaN(date.valueOf());
}

function validateTimestamp (timestamp: UnixTime) {
return Number.isInteger(timestamp);
}

0 comments on commit f6ff259

Please sign in to comment.