Starting signup creation of user. MySQL cannot return after insert and requerying with username.

This commit is contained in:
Bradley Shellnut 2024-02-06 17:08:03 -08:00
parent 3663fc328e
commit 8e1d453c13
4 changed files with 49 additions and 61 deletions

View file

@ -2,8 +2,6 @@ import { drizzle } from 'drizzle-orm/mysql2';
import mysql from 'mysql2/promise'; import mysql from 'mysql2/promise';
import { DATABASE_USER, DATABASE_PASSWORD, DATABASE_HOST, DATABASE_DB } from '$env/static/private'; import { DATABASE_USER, DATABASE_PASSWORD, DATABASE_HOST, DATABASE_DB } from '$env/static/private';
console.log('DATABASE_URL', process.env.DATABASE_URL);
// create the connection // create the connection
const connection = await mysql.createConnection({ const connection = await mysql.createConnection({
user: DATABASE_USER, user: DATABASE_USER,

View file

@ -1,4 +1,4 @@
import {fail, error, type Actions, redirect} from '@sveltejs/kit'; import { fail, error, type Actions, redirect } from '@sveltejs/kit';
import { superValidate } from 'sveltekit-superforms/server'; import { superValidate } from 'sveltekit-superforms/server';
import type { PageServerLoad } from './$types'; import type { PageServerLoad } from './$types';
import prisma from '$lib/prisma'; import prisma from '$lib/prisma';
@ -7,6 +7,9 @@ import { Argon2id } from 'oslo/password';
import { userSchema } from '$lib/config/zod-schemas'; import { userSchema } from '$lib/config/zod-schemas';
import { add_user_to_role } from '$server/roles'; import { add_user_to_role } from '$server/roles';
import type { Message } from '$lib/types.js'; import type { Message } from '$lib/types.js';
import db from '$lib/drizzle';
import { users } from '../../../schema';
import { eq } from 'drizzle-orm';
const signUpSchema = userSchema const signUpSchema = userSchema
.pick({ .pick({
@ -59,38 +62,40 @@ export const actions: Actions = {
const hashedPassword = await new Argon2id().hash(form.data.password); const hashedPassword = await new Argon2id().hash(form.data.password);
const user = await prisma.user.create({ await db.insert(users)
data: { .values({
username: form.data.username, username: form.data.username,
hashed_password: hashedPassword, hashed_password: hashedPassword,
email: form.data.email || '', email: form.data.email || '',
firstName: form.data.firstName || '', first_name: form.data.firstName || '',
lastName: form.data.lastName || '', last_name: form.data.lastName || '',
verified: false, verified: false,
receiveEmail: false, receive_email: false,
theme: 'system' theme: 'system'
} });
}); const user = await db.select()
.from(users)
.where(eq(users.username, form.data.username));
console.log('signup user', user); console.log('signup user', user);
add_user_to_role(user.id, 'user'); add_user_to_role(user[0].id, 'user');
await prisma.collection.create({ // await prisma.collection.create({
data: { // data: {
user_id: user.id // user_id: user.id
} // }
}); // });
await prisma.wishlist.create({ // await prisma.wishlist.create({
data: { // data: {
user_id: user.id // user_id: user.id
} // }
}); // });
console.log('User', user); // console.log('User', user);
session = await lucia.createSession(user.id, { // session = await lucia.createSession(user.id, {
ipCountry: event.locals.session?.ipCountry, // ipCountry: event.locals.session?.ipCountry,
ipAddress: event.locals.session?.ipAddress // ipAddress: event.locals.session?.ipAddress
}); // });
sessionCookie = lucia.createSessionCookie(session.id); // sessionCookie = lucia.createSessionCookie(session.id);
} catch (e: any) { } catch (e: any) {
if (e.message.toUpperCase() === `DUPLICATE_KEY_ID`) { if (e.message.toUpperCase() === `DUPLICATE_KEY_ID`) {
// key already exists // key already exists
@ -106,10 +111,10 @@ export const actions: Actions = {
error(500, message); error(500, message);
} }
event.cookies.set(sessionCookie.name, sessionCookie.value, { // event.cookies.set(sessionCookie.name, sessionCookie.value, {
path: ".", // path: ".",
...sessionCookie.attributes // ...sessionCookie.attributes
}); // });
redirect(302, '/'); redirect(302, '/');
// const message = { type: 'success', message: 'Signed Up!' } as const; // const message = { type: 'success', message: 'Signed Up!' } as const;

View file

@ -1,7 +1,7 @@
// import prisma from '$lib/prisma.js'; // import prisma from '$lib/prisma.js';
import db from '$lib/drizzle.js'; import db from '$lib/drizzle.js';
import { error, json } from '@sveltejs/kit'; import { error, json } from '@sveltejs/kit';
import { asc, inArray, sql } from 'drizzle-orm'; import { asc, count, inArray, sql } from 'drizzle-orm';
import { games, type Games } from '../../../../schema.js'; import { games, type Games } from '../../../../schema.js';
export const GET = async ({ url, locals }) => { export const GET = async ({ url, locals }) => {
@ -12,37 +12,22 @@ export const GET = async ({ url, locals }) => {
error(400, { message: 'Limit must be between 1 and 6' }); error(400, { message: 'Limit must be between 1 and 6' });
} }
// const totalGames = await prisma.game.count();
try { try {
console.log('db', db); const totalGames = await db
const dbGames = await db.select({ .select({
count: sql<number>`cast(count(*) as int))`, value: count(games.id)
}).from(games); })
console.log('count', dbGames[0].count); .from(games);
const randomIndex = Math.floor(Math.random() * dbGames[0]?.count); const numberOfGames = totalGames[0].value || 0;
const ids = await db.select({ id: games.id }) const randomIndex = Math.floor(Math.random() * numberOfGames);
const randomGames: Games[] = await db.select()
.from(games) .from(games)
.orderBy(asc(games.id)) .orderBy(asc(games.id))
.limit(limit) .limit(limit)
.offset(randomIndex); .offset(randomIndex);
// const ids: { id: string }[] = await prisma.$queryRaw`
// SELECT id
// FROM games
// ORDER BY id
// LIMIT ${limit}
// OFFSET ${randomIndex}
// `;
const randomGames: Games[] = await db.select().from(games).where(inArray(games.id, ids));
return json(randomGames); return json(randomGames);
} catch (e) { } catch (e) {
console.error(e); console.error(e);
throw error(500, { message: 'Something went wrong' }); throw error(500, { message: 'Something went wrong' });
} }
// const randomGames: Game[] = await prisma.game.findMany({
// where: {
// id: {
// in: ids.map(id => id.id)
// }
// }
// });
} }

View file

@ -10,25 +10,25 @@ export const users = mysqlTable("users", {
username: varchar("username", { username: varchar("username", {
length: 255 length: 255
}).unique(), }).unique(),
hashedPassword: varchar("hashed_password", { hashed_password: varchar("hashed_password", {
length: 255 length: 255
}), }),
email: varchar("email", { email: varchar("email", {
length: 255 length: 255
}).unique(), }).unique(),
firstName: varchar("first_name", { first_name: varchar("first_name", {
length: 255 length: 255
}), }),
lastName: varchar("last_name", { last_name: varchar("last_name", {
length: 255 length: 255
}), }),
verified: boolean("verified").default(false), verified: boolean("verified").default(false),
receiveEmail: boolean("receive_email").default(false), receive_email: boolean("receive_email").default(false),
theme: varchar("theme", { theme: varchar("theme", {
length: 255 length: 255
}).default("system"), }).default("system"),
createdAt: datetime("created_at").default(sql`(now(6))`), created_at: datetime("created_at").default(sql`(now(6))`),
updatedAt: datetime("updated_at").default(sql`(now(6))`) updated_at: datetime("updated_at").default(sql`(now(6))`)
}); });
export const user_relations = relations(users, ({ many }) => ({ export const user_relations = relations(users, ({ many }) => ({