diff --git a/src/database/deserializer.ts b/src/database/deserializer.ts new file mode 100644 index 0000000..cd32e7d --- /dev/null +++ b/src/database/deserializer.ts @@ -0,0 +1,17 @@ +import fs from "fs"; +import { NotificationDatabase } from "../types/notification"; + +/** + * Loads and deserializes database from JSON formatted file. + */ +export function loadDatabase(file: string): NotificationDatabase { + const text = fs.readFileSync(file).toString(); + return deserializeDatabase(text); +} + +/** + * Deserializes database from JSON format. + */ +export function deserializeDatabase(json: string): NotificationDatabase { + return JSON.parse(json) as NotificationDatabase; +} \ No newline at end of file diff --git a/src/database/index.ts b/src/database/index.ts new file mode 100644 index 0000000..0c45e43 --- /dev/null +++ b/src/database/index.ts @@ -0,0 +1,2 @@ +export { serializeDatabase } from "./serializer"; +export { deserializeDatabase } from "./deserializer"; \ No newline at end of file diff --git a/src/database/serializer.ts b/src/database/serializer.ts new file mode 100644 index 0000000..3775fb1 --- /dev/null +++ b/src/database/serializer.ts @@ -0,0 +1,34 @@ +import fs from "fs"; +import { Task } from "../types/task"; +import { Notification, NotificationDatabase } from "../types/notification"; + +/** + * Applies the mapper for each task from list, groups them by time and dumps the data into JSON formatted file. + */ +export function dumpDatabase(file: string, tasks: Task[], mapper: (task: Task) => Notification[]) { + const data = serializeDatabase(tasks, mapper); + fs.writeFileSync(file, data); +} + +/** + * Applies the mapper for each task from list, groups them by time and serializes into JSON format. + */ +export function serializeDatabase(tasks: Task[], mapper: (task: Task) => Notification[]): string { + const output = tasks.flatMap(wrapWithTimeFiller(mapper)).reduce((acc, n) => { + if (n.time) { + (acc[n.time] = (acc[n.time] || [])).push(n); + }; + + return acc; + }, {} as NotificationDatabase); + + return JSON.stringify(output); +} + +function wrapWithTimeFiller(mapper: (task: Task) => Notification[]): (task: Task) => Notification[] { + return (task: Task) => mapper(task) + .map(notification => ({ + ...notification, + time: task.reminder ?? notification.time, + })); +} \ No newline at end of file diff --git a/src/types/notification.ts b/src/types/notification.ts new file mode 100644 index 0000000..85511d7 --- /dev/null +++ b/src/types/notification.ts @@ -0,0 +1,9 @@ +import dayjs, { Dayjs } from "dayjs" + +export type Notification = { + time?: string; + title: string; + text: string; +}; + +export type NotificationDatabase = Record; \ No newline at end of file