Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 11x | import * as dates from 'date-fns';
import * as DB from '$lib/database';
import type { RuntimeValue } from '$lib/schemas/metadata';
import { mapValues } from '$lib/utils';
/**
* Serialize a metadata value for storing in the database.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function serializeMetadataValue(value: any): string {
return JSON.stringify(
value instanceof Date && dates.isValid(value)
? dates.format(value, "yyyy-MM-dd'T'HH:mm:ss")
: value
);
}
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('serializeMetadataValue', () => {
expect(serializeMetadataValue('hello')).toBe('"hello"');
expect(serializeMetadataValue(42)).toBe('42');
expect(serializeMetadataValue(true)).toBe('true');
expect(serializeMetadataValue(null)).toBe('null');
const date = new Date('2023-01-01T12:30:45');
expect(serializeMetadataValue(date)).toBe('"2023-01-01T12:30:45"');
// Invalid date should be serialized as is
const invalidDate = new Date('invalid');
expect(serializeMetadataValue(invalidDate)).toBe('null'); // Invalid date becomes null when JSON stringified
expect(serializeMetadataValue(['a', 'b'])).toBe('["a","b"]');
expect(serializeMetadataValue({ key: 'value' })).toBe('{"key":"value"}');
});
}
/**
* Serialize a full metadata value (including confidence, alternatives, etc)
*/
export function serializeMetadataFullValue<T extends { value: RuntimeValue }>({
value,
...rest
}: T): T & { value: string } {
return { ...rest, value: serializeMetadataValue(value) };
}
/**
* Serialize a record of metadata values for storing in the database.
*/
export function serializeMetadataValues(values: DB.MetadataValues): DB.MetadataValues {
return mapValues(values, serializeMetadataFullValue);
}
|