diff --git a/src/index.ts b/src/index.ts index 5aabd21..ac090a9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,6 +10,7 @@ import * as Color from './types/color'; import * as ConceptType from './types/concept-type'; import * as Date from './types/date'; import * as DateTime from './types/date-time'; +import * as DateTimeTZ from './types/date-time-tz'; import * as File from './types/file'; import * as ForeignKey from './types/foreign-key'; import * as Hashed from './types/hashed'; @@ -36,6 +37,7 @@ export interface Types { ConceptType: ConceptType.Types; Date: Date.Types; 'Date Time': DateTime.Types; + 'Date Time TZ': DateTimeTZ.Types; File: File.Types; ForeignKey: ForeignKey.Types; Hashed: Hashed.Types; @@ -60,6 +62,7 @@ export default { Color, ConceptType, 'Date Time': DateTime, + 'Date Time TZ': DateTimeTZ, Date, File, ForeignKey, diff --git a/src/types/date-time-tz.ts b/src/types/date-time-tz.ts new file mode 100644 index 0000000..f6d9d26 --- /dev/null +++ b/src/types/date-time-tz.ts @@ -0,0 +1,48 @@ +import type { + CurrentTimestampNode, + LessThanNode, +} from '@balena/abstract-sql-compiler'; +import * as TypeUtils from '../type-utils'; + +export const types = { + postgres: 'TIMESTAMPTZ', + mysql: 'TIMESTAMP', + websql: 'INTEGER', + odata: { + name: 'Edm.DateTimeOffset', + }, +}; + +export type Types = TypeUtils.TsTypes; +type DbWriteType = Date; + +export const fetchProcessing: TypeUtils.FetchProcessing = ( + data, +) => { + if (data == null) { + return data; + } + let date: Date; + if (data instanceof Date) { + date = data; + } else if (typeof data === 'string' || typeof data === 'number') { + date = new Date(data); + } else { + throw new Error('Fetched date time is not valid: ' + typeof data); + } + return date.toISOString(); +}; + +export const nativeFactTypes: TypeUtils.NativeFactTypes = { + 'Date Time TZ': { + ...TypeUtils.nativeFactTypeTemplates.equality, + 'is before': (from, to): LessThanNode => ['LessThan', from, to], + }, +}; + +export const nativeNames: TypeUtils.NativeNames = { + 'Current Time': ['CurrentTimestamp'] satisfies CurrentTimestampNode, +}; + +export const validate: TypeUtils.Validate = + TypeUtils.validate.date; diff --git a/test/Date Time TZ.ts b/test/Date Time TZ.ts new file mode 100644 index 0000000..409d86e --- /dev/null +++ b/test/Date Time TZ.ts @@ -0,0 +1,17 @@ +import * as helpers from './helpers'; + +helpers.describe('Date Time TZ', function (test) { + const now = new Date(); + describe('fetchProcessing', function () { + test.fetch(now, now.toISOString()); + test.fetch(now.toString(), new Date(now.toString()).toISOString()); + test.fetch(now.getTime(), new Date(now.getTime()).toISOString()); + test.fetch(null, null); + }); + + describe('validate', function () { + test.validate(now, true, now); + test.validate(now.getTime(), true, now); + test.validate(now.toString(), true, now); + }); +});