Skip to content

Commit

Permalink
updated with drizzle
Browse files Browse the repository at this point in the history
  • Loading branch information
AvidDabbler committed Jan 28, 2024
1 parent 80f5bfc commit ed0e62d
Show file tree
Hide file tree
Showing 7 changed files with 68 additions and 113 deletions.
57 changes: 19 additions & 38 deletions app/models/note.server.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,33 @@
import type { User, Note } from "@prisma/client";
import { eq } from "drizzle-orm";

import { prisma } from "~/db.server";
import { db } from "drizzle/config";
import { note } from "drizzle/schema";
import { dbDate } from "~/utils";

export function getNote({
id,
userId,
}: Pick<Note, "id"> & {
userId: User["id"];
}) {
return prisma.note.findFirst({
select: { id: true, body: true, title: true },
where: { id, userId },
});
export async function getNote({ id }: { id: string }) {
const [note] = await db.select().from(note).where(eq(note.id, id)).limit(1);

Check failure on line 8 in app/models/note.server.ts

View workflow job for this annotation

GitHub Actions / ʦ TypeScript

'note' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.

Check failure on line 8 in app/models/note.server.ts

View workflow job for this annotation

GitHub Actions / ʦ TypeScript

Block-scoped variable 'note' used before its declaration.

Check failure on line 8 in app/models/note.server.ts

View workflow job for this annotation

GitHub Actions / ʦ TypeScript

Block-scoped variable 'note' used before its declaration.
return note;
}

export function getNoteListItems({ userId }: { userId: User["id"] }) {
return prisma.note.findMany({
where: { userId },
select: { id: true, title: true },
orderBy: { updatedAt: "desc" },
});
export function getNoteListItems() {
return db
.select({ id: note.id, title: note.title })
.from(note)
.orderBy(note.createdAt);
}

export function createNote({
body,
title,
userId,
}: Pick<Note, "body" | "title"> & {
userId: User["id"];
}: {
body: string;
title: string;
userId: string;
}) {
return prisma.note.create({
data: {
title,
body,
user: {
connect: {
id: userId,
},
},
},
});
return db.insert(note).values([{ body, title, userId, updatedAt: dbDate() }]);
}

export function deleteNote({
id,
userId,
}: Pick<Note, "id"> & { userId: User["id"] }) {
return prisma.note.deleteMany({
where: { id, userId },
});
export function deleteNote({ id }: { id: string }) {
return db.delete(note).where(eq(note.id, id));
}
74 changes: 37 additions & 37 deletions app/models/user.server.ts
Original file line number Diff line number Diff line change
@@ -1,63 +1,63 @@
import type { Password, User } from "@prisma/client";
import bcrypt from "bcryptjs";
import { eq } from "drizzle-orm";

import { prisma } from "~/db.server";
import { db } from "drizzle/config";
import { password, user } from "drizzle/schema";

export type { User } from "@prisma/client";

export async function getUserById(id: User["id"]) {
return prisma.user.findUnique({ where: { id } });
export async function getUserById(id: string) {
const [_user] = await db.select().from(user).where(eq(user.id, id)).limit(1);
return _user;
}

export async function getUserByEmail(email: User["email"]) {
return prisma.user.findUnique({ where: { email } });
export async function getUserByEmail(email: string) {
const [_user] = await db.select().from(user).where(eq(user.email, email));
return _user;
}

export async function createUser(email: User["email"], password: string) {
const hashedPassword = await bcrypt.hash(password, 10);
export async function createUser(email: string, _password: string) {
const hashedPassword = await bcrypt.hash(_password, 10);

return prisma.user.create({
data: {
email,
password: {
create: {
hash: hashedPassword,
return await db.transaction(async (tx) => {
const [createdUser] = await tx
.insert(user)
.values([
{
email,
updatedAt: new Date().toLocaleDateString(),
},
},
},
])
.returning({ id: user.id, email: user.email });
await tx.insert(password).values({
userId: createdUser.id,
hash: hashedPassword,
});
return createdUser;
});
}

export async function deleteUserByEmail(email: User["email"]) {
return prisma.user.delete({ where: { email } });
export async function deleteUserByEmail(email: string) {
return await db.delete(user).where(eq(user.email, email));
}

export async function verifyLogin(
email: User["email"],
password: Password["hash"],
) {
const userWithPassword = await prisma.user.findUnique({
where: { email },
include: {
password: true,
},
});
export async function verifyLogin(email: string, _password: string) {
const [userWithPassword] = await db
.select()
.from(user)
.leftJoin(password, eq(password.userId, user.id))
.where(eq(user.email, email));

if (!userWithPassword || !userWithPassword.password) {
if (!userWithPassword || !userWithPassword.Password) {
return null;
}

const isValid = await bcrypt.compare(
password,
userWithPassword.password.hash,
_password,
userWithPassword.Password.hash,
);

if (!isValid) {
return null;
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { password: _password, ...userWithoutPassword } = userWithPassword;

return userWithoutPassword;
return userWithPassword.User;
}
5 changes: 1 addition & 4 deletions app/session.server.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { createCookieSessionStorage, redirect } from "@remix-run/node";
import invariant from "tiny-invariant";

import type { User } from "~/models/user.server";
import { getUserById } from "~/models/user.server";

invariant(process.env.SESSION_SECRET, "SESSION_SECRET must be set");
Expand All @@ -24,9 +23,7 @@ export async function getSession(request: Request) {
return sessionStorage.getSession(cookie);
}

export async function getUserId(
request: Request,
): Promise<User["id"] | undefined> {
export async function getUserId(request: Request) {
const session = await getSession(request);
const userId = session.get(USER_SESSION_KEY);
return userId;
Expand Down
12 changes: 7 additions & 5 deletions app/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { useMatches } from "@remix-run/react";
import { useMemo } from "react";

import type { User } from "~/models/user.server";

const DEFAULT_REDIRECT = "/";

/**
Expand Down Expand Up @@ -44,7 +42,7 @@ export function useMatchesData(
return route?.data as Record<string, unknown>;
}

function isUser(user: unknown): user is User {
function isUser(user: unknown) {
return (
user != null &&
typeof user === "object" &&
Expand All @@ -53,15 +51,15 @@ function isUser(user: unknown): user is User {
);
}

export function useOptionalUser(): User | undefined {
export function useOptionalUser() {
const data = useMatchesData("root");
if (!data || !isUser(data.user)) {
return undefined;
}
return data.user;
}

export function useUser(): User {
export function useUser() {
const maybeUser = useOptionalUser();
if (!maybeUser) {
throw new Error(
Expand All @@ -74,3 +72,7 @@ export function useUser(): User {
export function validateEmail(email: unknown): email is string {
return typeof email === "string" && email.length > 3 && email.includes("@");
}

export function dbDate() {
return new Date().toLocaleDateString();
}
4 changes: 3 additions & 1 deletion drizzle/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ export const password = sqliteTable(
);

export const note = sqliteTable("Note", {
id: text("id").primaryKey().notNull(),
id: text("id")
.primaryKey()
.$defaultFn(() => createId()),
title: text("title").notNull(),
body: text("body").notNull(),
createdAt: numeric("createdAt")
Expand Down
27 changes: 0 additions & 27 deletions app/seed2.ts → drizzle/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,33 +27,6 @@ async function seed() {
hash: hashedPassword,
});
});
// const user = await prisma.user.create({
// data: {
// email,
// password: {
// create: {
// hash: hashedPassword,
// },
// },
// },
// });
//
// await prisma.note.create({
// data: {
// title: "My first note",
// body: "Hello, world!",
// userId: user.id,
// },
// });
//
// await prisma.note.create({
// data: {
// title: "My second note",
// body: "Hello, world!",
// userId: user.id,
// },
// });
//
console.log(`Database has been seeded. 🌱`);
}

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"start": "remix-serve ./build/index.js",
"start:mocks": "binode --require ./mocks -- @remix-run/serve:remix-serve ./build/index.js",
"test": "vitest",
"seed": "tsx ./app/seed2.ts",
"seed": "tsx ./drizzle/seed.ts",
"gtfs": "tsx ./app/gtfs/index.ts",
"test:e2e:dev": "start-server-and-test dev http://localhost:3000 \"npx cypress open\"",
"pretest:e2e:run": "npm run build",
Expand Down

0 comments on commit ed0e62d

Please sign in to comment.