Add Server Data management
This commit is contained in:
@@ -1,15 +0,0 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const pathSchema = z.object({
|
||||
hello: z.string()
|
||||
});
|
||||
|
||||
const bodySchema = z.object({
|
||||
world: z.string()
|
||||
});
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const pathParams = await getValidatedRouterParams(event, pathSchema.parse);
|
||||
const body = await readValidatedBody(event, bodySchema.parse);
|
||||
return { risultato: `${pathParams.hello}-${body.world}` };
|
||||
});
|
||||
@@ -2,17 +2,15 @@ import { publicProcedure, router } from '~/server/trpc/init';
|
||||
import { z } from 'zod';
|
||||
|
||||
export const appRouter = router({
|
||||
hello: publicProcedure
|
||||
.input(
|
||||
z.object({
|
||||
text: z.string(),
|
||||
}),
|
||||
)
|
||||
.query((opts) => {
|
||||
return {
|
||||
greeting: `hello ${opts.input.text}`,
|
||||
};
|
||||
hello: publicProcedure.input(
|
||||
z.object({
|
||||
text: z.string(),
|
||||
}),
|
||||
).query((opts) => {
|
||||
return {
|
||||
greeting: `hello ${opts.input.text}`,
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
// export type definition of API
|
||||
|
||||
389
server/utils/data.ts
Normal file
389
server/utils/data.ts
Normal file
@@ -0,0 +1,389 @@
|
||||
import { matchSorter } from "match-sorter";
|
||||
// @ts-expect-error - no types, but it's a tiny function
|
||||
import sortBy from "sort-by";
|
||||
import invariant from "tiny-invariant";
|
||||
import { Low } from "lowdb";
|
||||
import { JSONFile } from "lowdb/node";
|
||||
import { join } from "node:path";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
|
||||
type ContactMutation = {
|
||||
id?: string;
|
||||
first?: string;
|
||||
last?: string;
|
||||
avatar?: string;
|
||||
twitter?: string;
|
||||
notes?: string;
|
||||
favorite?: boolean;
|
||||
};
|
||||
|
||||
export type ContactRecord = ContactMutation & {
|
||||
id: string;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
// Define the database schema
|
||||
type Schema = {
|
||||
records: 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[]> {
|
||||
const db = await getDb();
|
||||
return Object.keys(db.data.records)
|
||||
.map((key) => db.data.records[key])
|
||||
.sort(sortBy("-createdAt", "last"));
|
||||
},
|
||||
|
||||
async get(id: string): Promise<ContactRecord | null> {
|
||||
const db = await getDb();
|
||||
return db.data.records[id] || null;
|
||||
},
|
||||
|
||||
async create(values: ContactMutation): Promise<ContactRecord> {
|
||||
const db = await getDb();
|
||||
const id = values.id || Math.random().toString(36).substring(2, 9);
|
||||
const createdAt = new Date().toISOString();
|
||||
const newContact = { id, createdAt, ...values };
|
||||
db.data.records[id] = newContact;
|
||||
await db.write();
|
||||
return newContact;
|
||||
},
|
||||
|
||||
async set(id: string, values: ContactMutation): Promise<ContactRecord> {
|
||||
const db = await getDb();
|
||||
const contact = await this.get(id);
|
||||
invariant(contact, `No contact found for ${id}`);
|
||||
const updatedContact = { ...contact, ...values };
|
||||
db.data.records[id] = updatedContact;
|
||||
await db.write();
|
||||
return updatedContact;
|
||||
},
|
||||
|
||||
async destroy(id: string): Promise<null> {
|
||||
const db = await getDb();
|
||||
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
|
||||
if (db.data.records[id] !== undefined) delete db.data.records[id];
|
||||
await db.write();
|
||||
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);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
// Handful of helper functions to be called from route loaders and actions
|
||||
export async function getContacts(query?: string | null) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
let contacts = await fakeContacts.getAll();
|
||||
if (query) {
|
||||
contacts = matchSorter(contacts, query, {
|
||||
keys: ["first", "last"],
|
||||
});
|
||||
}
|
||||
return contacts.sort(sortBy("last", "createdAt"));
|
||||
}
|
||||
|
||||
export async function createEmptyContact() {
|
||||
return await fakeContacts.create({});
|
||||
}
|
||||
|
||||
export async function getContact(id: string) {
|
||||
return fakeContacts.get(id);
|
||||
}
|
||||
|
||||
export async function updateContact(id: string, updates: ContactMutation) {
|
||||
const contact = await fakeContacts.get(id);
|
||||
if (!contact) {
|
||||
throw new Error(`No contact found for ${id}`);
|
||||
}
|
||||
await fakeContacts.set(id, { ...contact, ...updates });
|
||||
return contact;
|
||||
}
|
||||
|
||||
export async function deleteContact(id: string) {
|
||||
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:
|
||||
"https://sessionize.com/image/124e-400o400o2-wHVdAuNaxi8KJrgtN3ZKci.jpg",
|
||||
first: "Shruti",
|
||||
last: "Kapoor",
|
||||
twitter: "@shrutikapoor08",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/1940-400o400o2-Enh9dnYmrLYhJSTTPSw3MH.jpg",
|
||||
first: "Glenn",
|
||||
last: "Reyes",
|
||||
twitter: "@glnnrys",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/9273-400o400o2-3tyrUE3HjsCHJLU5aUJCja.jpg",
|
||||
first: "Ryan",
|
||||
last: "Florence",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/d14d-400o400o2-pyB229HyFPCnUcZhHf3kWS.png",
|
||||
first: "Oscar",
|
||||
last: "Newman",
|
||||
twitter: "@__oscarnewman",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/fd45-400o400o2-fw91uCdGU9hFP334dnyVCr.jpg",
|
||||
first: "Michael",
|
||||
last: "Jackson",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/b07e-400o400o2-KgNRF3S9sD5ZR4UsG7hG4g.jpg",
|
||||
first: "Christopher",
|
||||
last: "Chedeau",
|
||||
twitter: "@Vjeux",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/262f-400o400o2-UBPQueK3fayaCmsyUc1Ljf.jpg",
|
||||
first: "Cameron",
|
||||
last: "Matheson",
|
||||
twitter: "@cmatheson",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/820b-400o400o2-Ja1KDrBAu5NzYTPLSC3GW8.jpg",
|
||||
first: "Brooks",
|
||||
last: "Lybrand",
|
||||
twitter: "@BrooksLybrand",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/df38-400o400o2-JwbChVUj6V7DwZMc9vJEHc.jpg",
|
||||
first: "Alex",
|
||||
last: "Anderson",
|
||||
twitter: "@ralex1993",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/5578-400o400o2-BMT43t5kd2U1XstaNnM6Ax.jpg",
|
||||
first: "Kent C.",
|
||||
last: "Dodds",
|
||||
twitter: "@kentcdodds",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/c9d5-400o400o2-Sri5qnQmscaJXVB8m3VBgf.jpg",
|
||||
first: "Nevi",
|
||||
last: "Shah",
|
||||
twitter: "@nevikashah",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/2694-400o400o2-MYYTsnszbLKTzyqJV17w2q.png",
|
||||
first: "Andrew",
|
||||
last: "Petersen",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/907a-400o400o2-9TM2CCmvrw6ttmJiTw4Lz8.jpg",
|
||||
first: "Scott",
|
||||
last: "Smerchek",
|
||||
twitter: "@smerchek",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/08be-400o400o2-WtYGFFR1ZUJHL9tKyVBNPV.jpg",
|
||||
first: "Giovanni",
|
||||
last: "Benussi",
|
||||
twitter: "@giovannibenussi",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/f814-400o400o2-n2ua5nM9qwZA2hiGdr1T7N.jpg",
|
||||
first: "Igor",
|
||||
last: "Minar",
|
||||
twitter: "@IgorMinar",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/fb82-400o400o2-LbvwhTVMrYLDdN3z4iEFMp.jpeg",
|
||||
first: "Brandon",
|
||||
last: "Kish",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/fcda-400o400o2-XiYRtKK5Dvng5AeyC8PiUA.png",
|
||||
first: "Arisa",
|
||||
last: "Fukuzaki",
|
||||
twitter: "@arisa_dev",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/c8c3-400o400o2-PR5UsgApAVEADZRixV4H8e.jpeg",
|
||||
first: "Alexandra",
|
||||
last: "Spalato",
|
||||
twitter: "@alexadark",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/7594-400o400o2-hWtdCjbdFdLgE2vEXBJtyo.jpg",
|
||||
first: "Cat",
|
||||
last: "Johnson",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/5636-400o400o2-TWgi8vELMFoB3hB9uPw62d.jpg",
|
||||
first: "Ashley",
|
||||
last: "Narcisse",
|
||||
twitter: "@_darkfadr",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/6aeb-400o400o2-Q5tAiuzKGgzSje9ZsK3Yu5.JPG",
|
||||
first: "Edmund",
|
||||
last: "Hung",
|
||||
twitter: "@_edmundhung",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/30f1-400o400o2-wJBdJ6sFayjKmJycYKoHSe.jpg",
|
||||
first: "Clifford",
|
||||
last: "Fajardo",
|
||||
twitter: "@cliffordfajard0",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/6faa-400o400o2-amseBRDkdg7wSK5tjsFDiG.jpg",
|
||||
first: "Erick",
|
||||
last: "Tamayo",
|
||||
twitter: "@ericktamayo",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/feba-400o400o2-R4GE7eqegJNFf3cQ567obs.jpg",
|
||||
first: "Paul",
|
||||
last: "Bratslavsky",
|
||||
twitter: "@codingthirty",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/c315-400o400o2-spjM5A6VVfVNnQsuwvX3DY.jpg",
|
||||
first: "Pedro",
|
||||
last: "Cattori",
|
||||
twitter: "@pcattori",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/eec1-400o400o2-HkvWKLFqecmFxLwqR9KMRw.jpg",
|
||||
first: "Andre",
|
||||
last: "Landgraf",
|
||||
twitter: "@AndreLandgraf94",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/c73a-400o400o2-4MTaTq6ftC15hqwtqUJmTC.jpg",
|
||||
first: "Monica",
|
||||
last: "Powell",
|
||||
twitter: "@indigitalcolor",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/cef7-400o400o2-KBZUydbjfkfGACQmjbHEvX.jpeg",
|
||||
first: "Brian",
|
||||
last: "Lee",
|
||||
twitter: "@brian_dlee",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/f83b-400o400o2-Pyw3chmeHMxGsNoj3nQmWU.jpg",
|
||||
first: "Sean",
|
||||
last: "McQuaid",
|
||||
twitter: "@SeanMcQuaidCode",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/a9fc-400o400o2-JHBnWZRoxp7QX74Hdac7AZ.jpg",
|
||||
first: "Shane",
|
||||
last: "Walker",
|
||||
twitter: "@swalker326",
|
||||
},
|
||||
{
|
||||
avatar:
|
||||
"https://sessionize.com/image/6644-400o400o2-aHnGHb5Pdu3D32MbfrnQbj.jpg",
|
||||
first: "Jon",
|
||||
last: "Jensen",
|
||||
twitter: "@jenseng",
|
||||
},
|
||||
].map(contact => ({
|
||||
...contact,
|
||||
id: `${contact.first
|
||||
.toLowerCase()
|
||||
.split(" ")
|
||||
.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();
|
||||
}
|
||||
})();
|
||||
Reference in New Issue
Block a user