Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: better db integration #29

Merged
merged 1 commit into from
Jan 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/lib/server/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { sha256 } from '@oslojs/crypto/sha2';
import { encodeBase64url, encodeHexLowerCase } from '@oslojs/encoding';
import { db } from '$lib/server/db';
import * as table from '$lib/server/db/schema';
import { insertSession } from './backend/user-service';

const DAY_IN_MS = 1000 * 60 * 60 * 24;

Expand All @@ -22,15 +23,14 @@ export async function createSession(token: string, userID: string) {
userID,
expiresAt: new Date(Date.now() + DAY_IN_MS * 30)
};
await db.insert(table.session).values(session);
await insertSession(session);
return session;
}

export async function validateSessionToken(token: string) {
const sessionId = encodeHexLowerCase(sha256(new TextEncoder().encode(token)));
const [result] = await db
.select({
// Adjust user table here to tweak returned data
user: table.user,
session: table.session
})
Expand Down
10 changes: 10 additions & 0 deletions src/lib/server/backend/reservation-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { db } from '$lib/server/db';
import { eq } from 'drizzle-orm';
import * as table from '$lib/server/db/schema';

export async function insertReservation(res: table.Reservation) {
await db
.insert(table.reservation)
.values({ date: res.date, id: res.id, userID: res.userID, serviceID: res.serviceID });
}

11 changes: 11 additions & 0 deletions src/lib/server/backend/services-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { db } from '$lib/server/db';
import { eq } from 'drizzle-orm';
import * as table from '$lib/server/db/schema';

export async function getAllServices() {
return await db.select().from(table.service);
}

export async function insertService(service: table.Service) {
await db.insert(table.service).values(service).onConflictDoNothing();
}
23 changes: 23 additions & 0 deletions src/lib/server/backend/user-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { db } from '$lib/server/db';
import { eq } from 'drizzle-orm';
import * as table from '$lib/server/db/schema';

export async function insertUser(user: table.User) {
await db.insert(table.user).values({
id: user.id,
email: user.email,
passwordHash: user.passwordHash,
lastName: user.lastName,
firstName: user.firstName
});
}

export async function getUser(email: string) {
return await db.select().from(table.user).where(eq(table.user.email, email));
}

export async function insertSession(session: table.Session) {
return await db.insert(table.session).values(session);
}

// const results = await db.select().from(table.user).where(eq(table.user.email, form.data.email));
5 changes: 3 additions & 2 deletions src/lib/server/db/init.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { db } from '$lib/server/db';
import type { Service } from './schema';
import * as table from '$lib/server/db/schema';
import { getAllServices, insertService } from '../backend/services-service';

export const init = async () => {
const result = await db.select().from(table.service);
const result = await getAllServices();
if (result.length === 0) {
services.forEach(async (ser) => {
await db.insert(table.service).values(ser).onConflictDoNothing();
await insertService(ser);
});
}

Expand Down
15 changes: 6 additions & 9 deletions src/routes/(protected)/newreservation/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@ import type { Actions, PageServerLoad } from './$types.js';
import { superValidate } from 'sveltekit-superforms';
import { reservation } from '$lib/schemas/reservation.js';
import { zod } from 'sveltekit-superforms/adapters';
import type { Service } from '$lib/server/db/schema.js';
import { fail } from '@sveltejs/kit';
import { db } from '$lib/server/db/index.js';
import * as table from '$lib/server/db/schema';
import { insertReservation } from '$lib/server/backend/reservation-service.js';
import { getAllServices } from '$lib/server/backend/services-service.js';

export const actions: Actions = {
default: async ({ request, locals }) => {
Expand Down Expand Up @@ -37,14 +36,12 @@ export const actions: Actions = {
if (!locals.user) {
return fail(404, { message: 'Riprova' });
} else {
const booking: table.Reservation = {
date: date,
await insertReservation({
date,
id: crypto.randomUUID(),
userID: locals.user.id,
serviceID: service
};

await db.insert(table.reservation).values(booking);
});
return {
bookingCreated: true
};
Expand All @@ -53,7 +50,7 @@ export const actions: Actions = {
};

export const load: PageServerLoad = async () => {
const services = await db.select().from(table.service);
const services = await getAllServices();
return {
services,
form: await superValidate(zod(reservation))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
data: TData[];
};

// @ts-expect-error
let { data, columns }: DataTableProps<TData, TValue> = $props();

const table = createSvelteTable({
Expand Down
6 changes: 2 additions & 4 deletions src/routes/login/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { verify } from '@node-rs/argon2';
import { fail, redirect } from '@sveltejs/kit';
import { eq } from 'drizzle-orm';
import * as auth from '$lib/server/auth';
import { db } from '$lib/server/db';
import * as table from '$lib/server/db/schema';
import type { Actions, PageServerLoad } from './$types';
import { superValidate } from 'sveltekit-superforms';
import { zod } from 'sveltekit-superforms/adapters';
import { login } from '$lib/schemas/login';
import { getUser } from '$lib/server/backend/user-service';

export const load: PageServerLoad = async (event) => {
if (event.locals.user) {
Expand All @@ -29,7 +27,7 @@ export const actions: Actions = {
});
}

const results = await db.select().from(table.user).where(eq(table.user.email, form.data.email));
const results = await getUser(form.data.email);

const existingUser = results.at(0);
if (!existingUser) {
Expand Down
5 changes: 2 additions & 3 deletions src/routes/prices/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import type { PageServerLoad } from './$types.js';
import { db } from '$lib/server/db/index.js';
import * as table from '$lib/server/db/schema.js';
import { getAllServices } from '$lib/server/backend/services-service.js';

export const load: PageServerLoad = async () => {
return {
services: await db.select().from(table.service)
services: await getAllServices()
};
};
12 changes: 5 additions & 7 deletions src/routes/signup/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { fail, redirect } from '@sveltejs/kit';
import * as auth from '$lib/server/auth';
import { db } from '$lib/server/db';
import { eq } from 'drizzle-orm';
import * as table from '$lib/server/db/schema';
import { hash } from '@node-rs/argon2';
import { encodeBase32LowerCase } from '@oslojs/encoding';
import type { Actions, PageServerLoad } from './$types';
import { superValidate } from 'sveltekit-superforms';
import { zod } from 'sveltekit-superforms/adapters';
import { signup } from '$lib/schemas/signup';
import { getUser, insertUser } from '$lib/server/backend/user-service';

export const load: PageServerLoad = async (event) => {
if (event.locals.user) {
Expand All @@ -30,7 +28,7 @@ export const actions: Actions = {
});
}

const results = await db.select().from(table.user).where(eq(table.user.email, form.data.email));
const results = await getUser(form.data.email);

const existingUser = results.at(0);
if (existingUser) {
Expand All @@ -42,7 +40,7 @@ export const actions: Actions = {

const { email, password, firstName, lastName } = form.data;

const userId = generateUserId();
const userID = generateUserId();
const passwordHash = await hash(password, {
// recommended minimum parameters
memoryCost: 19456,
Expand All @@ -52,10 +50,10 @@ export const actions: Actions = {
});

try {
await db.insert(table.user).values({ id: userId, email, passwordHash, lastName, firstName });
await insertUser({ id: userID, email, passwordHash, lastName, firstName, phoneNumber: null });

const sessionToken = auth.generateSessionToken();
const session = await auth.createSession(sessionToken, userId);
const session = await auth.createSession(sessionToken, userID);
auth.setSessionTokenCookie(event, sessionToken, session.expiresAt);
} catch (e) {
console.log(e);
Expand Down
Loading