Skip to content

Commit

Permalink
Drop default translation and use exception to enforce type safety
Browse files Browse the repository at this point in the history
Signed-off-by: Gavin <gavinfreeborn@gmail.com>
  • Loading branch information
Gavinok committed Jun 20, 2023
1 parent df985a8 commit e7cbb7e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
<script setup lang="ts">
import Dropdown from 'primevue/dropdown';
import { useI18n } from 'vue-i18n';
import { i18nLocale } from '@/helpers';
import { I18nLocale } from '@/helpers';
const { locale } = useI18n({ useScope: 'global' });
const localeList: Array<i18nLocale> = ['en', 'fr', 'jp'];
const localeList: Array<I18nLocale> = ['en', 'fr', 'jp'];
</script>

<style lang="scss" scoped>
Expand Down
30 changes: 19 additions & 11 deletions services/tenant-ui/frontend/src/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,40 @@ import { format, fromUnixTime, parseJSON } from 'date-fns';
import { enCA, fr, ja } from 'date-fns/locale';
import { useI18n } from 'vue-i18n';

export type i18nLocale = 'en' | 'fr' | 'jp';
export type I18nLocale = 'en' | 'fr' | 'jp';

function i18n2DateLocale(i18nLocal: i18nLocale) {
switch (i18nLocal) {
function i18n2DateLocale(i18nLocale: I18nLocale): Locale {
switch (i18nLocale) {
case 'en':
return enCA;
case 'fr':
return fr;
case 'jp':
return ja;
default:
console.log(
`No valid translation found for ${i18nLocal} defaulting to enCA`
);
return enCA;
}
// This way we can fall back to a default while using typescript to
// enforce that all instances of i18nLocale have a corresponding case in the
// switch statement
/* eslint no-unreachable: "error" */
throw new Error('No valid date-fn');
}

function _dateFnsFormat(value: string, formatter: string) {
const { locale } = useI18n();
const formatted = '';
try {
if (value) {
return format(parseJSON(value), formatter, {
locale: i18n2DateLocale(locale.value as i18nLocale),
});
try {
return format(parseJSON(value), formatter, {
locale: i18n2DateLocale(locale.value as I18nLocale),
});
} catch {
// Incase the locale was never set (used outside of a vue component)
console.log(
`No valid translation found for ${locale.value} defaulting to enCA`
);
return format(parseJSON(value), formatter, { locale: enCA });
}
}
} catch (error) {
console.error(`_dateFnsFormat: Error parsing ${value} to ${error}`);
Expand Down

0 comments on commit e7cbb7e

Please sign in to comment.