Refine date parsing, update tests

This commit is contained in:
Sam Becker 2024-02-29 14:58:10 -06:00
parent 20fbcca862
commit fef580e8fa
4 changed files with 22 additions and 4 deletions

View File

@ -30,4 +30,16 @@ describe('Date utility', () => {
.toBe('2023-12-02 16:38:36'); .toBe('2023-12-02 16:38:36');
}); });
}); });
it('Empty string', () => {
const timestamp = ' ';
const offset = undefined;
expect(convertTimestampWithOffsetToPostgresString(
timestamp,
offset
))
.toBe(convertTimestampWithOffsetToPostgresString(
new Date().toISOString(),
offset
));
});
}); });

View File

@ -2,10 +2,12 @@ import { parameterize } from '@/utility/string';
describe('String', () => { describe('String', () => {
it('parameterizes', () => { it('parameterizes', () => {
expect(parameterize('my-tag')).toBe('my-tag');
expect(parameterize('my tag')).toBe('my-tag'); expect(parameterize('my tag')).toBe('my-tag');
expect(parameterize('My Tag')).toBe('my-tag'); expect(parameterize('My Tag')).toBe('my-tag');
expect(parameterize('my_tag')).toBe('my-tag'); expect(parameterize('my_tag')).toBe('my-tag');
expect(parameterize('person\'s tag')).toBe('persons-tag'); expect(parameterize('person\'s tag')).toBe('persons-tag');
expect(parameterize('"person\'s tag"')).toBe('persons-tag'); expect(parameterize('"person\'s tag"')).toBe('persons-tag');
expect(parameterize('宿宿宿宿')).toBe('宿宿宿宿');
}); });
}); });

View File

@ -18,14 +18,16 @@ export const formatDateForPostgres = (date: Date) =>
'$1-$2-$3 $4', '$1-$2-$3 $4',
); );
const dateFromTimestamp = (timestamp?: AmbiguousTimestamp): Date => const dateFromTimestamp = (timestamp?: AmbiguousTimestamp): Date => {
typeof timestamp === 'number' const date = typeof timestamp === 'number'
? new Date(timestamp * 1000) ? new Date(timestamp * 1000)
: typeof timestamp === 'string' && timestamp.trim().length > 0 : typeof timestamp === 'string'
? /.+Z/i.test(timestamp) ? /.+Z/i.test(timestamp)
? new Date(timestamp) ? new Date(timestamp)
: new Date(`${timestamp}Z`) : new Date(`${timestamp}Z`)
: new Date(); : undefined;
return date && !isNaN(date.getTime()) ? date : new Date();
};
const createNaiveDateWithOffset = ( const createNaiveDateWithOffset = (
timestamp?: AmbiguousTimestamp, timestamp?: AmbiguousTimestamp,

View File

@ -24,6 +24,8 @@ export const parameterize = (
.trim() .trim()
// Replaces spaces, underscores, and dashes with dashes // Replaces spaces, underscores, and dashes with dashes
.replaceAll(/[\s_—]/gi, '-') .replaceAll(/[\s_—]/gi, '-')
// Removes punctuation
.replaceAll(/['"!@#$%^&*()_+=[\]{};:/?,.<>\\|`~]/gi, '')
// Removes all non-alphanumeric characters // Removes all non-alphanumeric characters
.replaceAll( .replaceAll(
shouldRemoveNonAlphanumeric shouldRemoveNonAlphanumeric