From 7ec41417cf1a409444c0759342bfbf18d16d0bb7 Mon Sep 17 00:00:00 2001 From: Balthasar Hofer Date: Sun, 7 Apr 2024 00:32:43 +0200 Subject: [PATCH] fix: ensure date-fns#parse is called with a string (#111) * fix: ensure date-fns#parse is called with a string * add test case for schoolyear * add comment to wrapper function `parse` --- __tests__/index.test.js | 15 ++++++++------- src/base.ts | 20 +++++++++++++++++++- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/__tests__/index.test.js b/__tests__/index.test.js index e8d1ea3..c168312 100644 --- a/__tests__/index.test.js +++ b/__tests__/index.test.js @@ -81,7 +81,7 @@ test('should method logout return true', async () => { cases( 'should getLatestSchoolyear return object', - async ({ validate }) => { + async ({ validate, dateFormat }) => { const name = 'testName'; const id = 'testId'; const untis = createInstance(); @@ -91,14 +91,14 @@ cases( { id, name, - startDate: '20191111', - endDate: '20191211', + startDate: dateFormat === 'string' ? '20191111' : 20191111, + endDate: dateFormat === 'string' ? '20191211' : 20191211, }, { id, name, - startDate: '20191113', - endDate: '20191115', + startDate: dateFormat === 'string' ? '20191113' : 20191113, + endDate: dateFormat === 'string' ? '20191115' : 20191115, }, ], }); @@ -111,8 +111,9 @@ cases( }); }, [ - { name: 'with validate', validate: true }, - { name: 'without validate', validate: false }, + { name: 'with validate, string date', validate: true, dateFormat: 'string' }, + { name: 'with validate, numeric date', validate: true, dateFormat: 'number' }, + { name: 'without validate, string date', validate: false, dateFormat: 'string' }, ] ); diff --git a/src/base.ts b/src/base.ts index 9f2ce08..cd75462 100644 --- a/src/base.ts +++ b/src/base.ts @@ -1,7 +1,7 @@ import { serialize } from './cookie'; import axios from 'axios'; import { btoa } from './base-64'; -import { parse, startOfDay, format } from 'date-fns'; +import { parse as fnsParse, startOfDay, format, type ParseOptions } from 'date-fns'; import type { AxiosInstance } from 'axios'; import type { Absences, @@ -25,6 +25,24 @@ import type { import type { InternalSchoolYear, SessionInformation } from './internal'; import { WebUntisElementType } from './types'; +/** + * Ensures that the dateStr is a string when calling {@link fnsParse}. + * This is needed since some WebUntis servers return numbers instead of strings. + * @param dateStr {string | number} + * @param formatStr {string} + * @param referenceDate {DateType | number | string} + * @param options {ParseOptions | undefined} + * @returns + */ +const parse = ( + dateStr: string | number, + formatStr: string, + referenceDate: DateType | number | string, + options?: ParseOptions, +) => { + return fnsParse(`${dateStr}`, formatStr, referenceDate, options); +}; + export class Base { school: string; schoolbase64: string;