New Data handler with lowdb

This commit is contained in:
2025-04-02 12:06:12 +02:00
parent a54d7b57ee
commit 94346dd242
3 changed files with 325 additions and 233 deletions

View File

@@ -9,6 +9,7 @@
"lint": "next lint" "lint": "next lint"
}, },
"dependencies": { "dependencies": {
"lowdb": "^7.0.1",
"match-sorter": "^8.0.0", "match-sorter": "^8.0.0",
"next": "15.2.4", "next": "15.2.4",
"react": "^19.0.0", "react": "^19.0.0",

17
pnpm-lock.yaml generated
View File

@@ -8,6 +8,9 @@ importers:
.: .:
dependencies: dependencies:
lowdb:
specifier: ^7.0.1
version: 7.0.1
match-sorter: match-sorter:
specifier: ^8.0.0 specifier: ^8.0.0
version: 8.0.0 version: 8.0.0
@@ -1121,6 +1124,10 @@ packages:
resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==} resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
hasBin: true hasBin: true
lowdb@7.0.1:
resolution: {integrity: sha512-neJAj8GwF0e8EpycYIDFqEPcx9Qz4GUho20jWFR7YiFeXzF1YMLdxB36PypcTSPMA+4+LvgyMacYhlr18Zlymw==}
engines: {node: '>=18'}
match-sorter@8.0.0: match-sorter@8.0.0:
resolution: {integrity: sha512-bGJ6Zb+OhzXe+ptP5d80OLVx7AkqfRbtGEh30vNSfjNwllu+hHI+tcbMIT/fbkx/FKN1PmKuDb65+Oofg+XUxw==} resolution: {integrity: sha512-bGJ6Zb+OhzXe+ptP5d80OLVx7AkqfRbtGEh30vNSfjNwllu+hHI+tcbMIT/fbkx/FKN1PmKuDb65+Oofg+XUxw==}
@@ -1407,6 +1414,10 @@ packages:
stable-hash@0.0.5: stable-hash@0.0.5:
resolution: {integrity: sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA==} resolution: {integrity: sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA==}
steno@4.0.2:
resolution: {integrity: sha512-yhPIQXjrlt1xv7dyPQg2P17URmXbuM5pdGkpiMB3RenprfiBlvK415Lctfe0eshk90oA7/tNq7WEiMK8RSP39A==}
engines: {node: '>=18'}
streamsearch@1.1.0: streamsearch@1.1.0:
resolution: {integrity: sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==} resolution: {integrity: sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==}
engines: {node: '>=10.0.0'} engines: {node: '>=10.0.0'}
@@ -2764,6 +2775,10 @@ snapshots:
dependencies: dependencies:
js-tokens: 4.0.0 js-tokens: 4.0.0
lowdb@7.0.1:
dependencies:
steno: 4.0.2
match-sorter@8.0.0: match-sorter@8.0.0:
dependencies: dependencies:
'@babel/runtime': 7.27.0 '@babel/runtime': 7.27.0
@@ -3100,6 +3115,8 @@ snapshots:
stable-hash@0.0.5: {} stable-hash@0.0.5: {}
steno@4.0.2: {}
streamsearch@1.1.0: {} streamsearch@1.1.0: {}
string.prototype.includes@2.0.1: string.prototype.includes@2.0.1:

View File

@@ -2,12 +2,16 @@
// 🛑 Nothing in here has anything to do with React Router, it's just a fake database // 🛑 Nothing in here has anything to do with React Router, it's just a fake database
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
// noinspection UnnecessaryLocalVariableJS,JSUnusedGlobalSymbols // noinspection UnnecessaryLocalVariableJS,JSUnusedGlobalSymbols
import "server-only" import "server-only";
import { matchSorter } from "match-sorter"; import { matchSorter } from "match-sorter";
// @ts-expect-error - no types, but it's a tiny function // @ts-expect-error - no types, but it's a tiny function
import sortBy from "sort-by"; import sortBy from "sort-by";
import invariant from "tiny-invariant"; import invariant from "tiny-invariant";
import { Low } from "lowdb";
import { JSONFile } from "lowdb/node";
import { join } from "path";
import { mkdir } from "fs/promises";
type ContactMutation = { type ContactMutation = {
id?: string; id?: string;
@@ -24,42 +28,97 @@ export type ContactRecord = ContactMutation & {
createdAt: string; createdAt: string;
}; };
//////////////////////////////////////////////////////////////////////////////// // Define the database schema
// This is just a fake DB table. In a real app you'd be talking to a real db or type Schema = {
// fetching from an existing API. records: Record<string, ContactRecord>;
const fakeContacts = { };
records: {} as Record<string, ContactRecord>,
// Set up lowdb
const initDb = async (): Promise<Low<Schema>> => {
// Ensure the db directory exists
const dbDir = join(process.cwd(), '.db');
await mkdir(dbDir, { recursive: true });
const file = join(dbDir, 'contacts.json');
const adapter = new JSONFile<Schema>(file);
const defaultData: Schema = { records: {} };
const db = new Low<Schema>(adapter, defaultData);
// Load existing data
await db.read();
// Initialize if needed
if (!db.data) {
db.data = defaultData;
}
return db;
};
// Create a singleton instance of the database
let dbPromise: Promise<Low<Schema>> | null = null;
const getDb = () => {
if (!dbPromise) {
dbPromise = initDb();
}
return dbPromise;
};
////////////////////////////////////////////////////////////////////////////////
// This is a DB wrapper using lowdb for persistence
const fakeContacts = {
async getAll(): Promise<ContactRecord[]> { async getAll(): Promise<ContactRecord[]> {
return Object.keys(fakeContacts.records) const db = await getDb();
.map((key) => fakeContacts.records[key]) return Object.keys(db.data.records)
.map((key) => db.data.records[key])
.sort(sortBy("-createdAt", "last")); .sort(sortBy("-createdAt", "last"));
}, },
async get(id: string): Promise<ContactRecord | null> { async get(id: string): Promise<ContactRecord | null> {
return fakeContacts.records[id] || null; const db = await getDb();
return db.data.records[id] || null;
}, },
async create(values: ContactMutation): Promise<ContactRecord> { async create(values: ContactMutation): Promise<ContactRecord> {
const db = await getDb();
const id = values.id || Math.random().toString(36).substring(2, 9); const id = values.id || Math.random().toString(36).substring(2, 9);
const createdAt = new Date().toISOString(); const createdAt = new Date().toISOString();
const newContact = { id, createdAt, ...values }; const newContact = { id, createdAt, ...values };
fakeContacts.records[id] = newContact; db.data.records[id] = newContact;
await db.write();
return newContact; return newContact;
}, },
async set(id: string, values: ContactMutation): Promise<ContactRecord> { async set(id: string, values: ContactMutation): Promise<ContactRecord> {
const contact = await fakeContacts.get(id); const db = await getDb();
const contact = await this.get(id);
invariant(contact, `No contact found for ${id}`); invariant(contact, `No contact found for ${id}`);
const updatedContact = { ...contact, ...values }; const updatedContact = { ...contact, ...values };
fakeContacts.records[id] = updatedContact; db.data.records[id] = updatedContact;
await db.write();
return updatedContact; return updatedContact;
}, },
destroy(id: string): null { async destroy(id: string): Promise<null> {
delete fakeContacts.records[id]; const db = await getDb();
delete db.data.records[id];
await db.write();
return null; return null;
}, },
// New reset function to restore the initial data
async reset(): Promise<void> {
const db = await getDb();
db.data.records = {};
await db.write();
// Restore initial data
const initialContacts = getInitialContacts();
for (const contact of initialContacts) {
await this.create(contact);
}
}
}; };
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
@@ -94,10 +153,18 @@ export async function updateContact(id: string, updates: ContactMutation) {
} }
export async function deleteContact(id: string) { export async function deleteContact(id: string) {
fakeContacts.destroy(id); await fakeContacts.destroy(id);
} }
[ // New function to reset the database to initial state
export async function resetDatabase() {
console.log("RESET DATABASE");
await fakeContacts.reset();
}
// Helper function to get initial contacts data
function getInitialContacts() {
return [
{ {
avatar: avatar:
"https://sessionize.com/image/124e-400o400o2-wHVdAuNaxi8KJrgtN3ZKci.jpg", "https://sessionize.com/image/124e-400o400o2-wHVdAuNaxi8KJrgtN3ZKci.jpg",
@@ -310,12 +377,19 @@ export async function deleteContact(id: string) {
last: "Jensen", last: "Jensen",
twitter: "@jenseng", twitter: "@jenseng",
}, },
].forEach((contact) => { ].map(contact => ({
fakeContacts.create({
...contact, ...contact,
id: `${contact.first id: `${contact.first
.toLowerCase() .toLowerCase()
.split(" ") .split(" ")
.join("_")}-${contact.last.toLocaleLowerCase()}`, .join("_")}-${contact.last.toLowerCase()}`,
}); }));
}); }
// Initialize with seed data on first load
(async () => {
const db = await getDb();
if (Object.keys(db.data.records).length === 0) {
await resetDatabase();
}
})();