Add support for database

This commit is contained in:
2025-01-17 14:05:30 +01:00
parent 3b7307dac3
commit 3919eed679
4 changed files with 62 additions and 0 deletions

View File

@@ -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;
}

2
src/database/index.ts Normal file
View File

@@ -0,0 +1,2 @@
export { serializeDatabase } from "./serializer";
export { deserializeDatabase } from "./deserializer";

View File

@@ -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,
}));
}

View File

@@ -0,0 +1,9 @@
import dayjs, { Dayjs } from "dayjs"
export type Notification = {
time?: string;
title: string;
text: string;
};
export type NotificationDatabase = Record<string, Notification[]>;