rykuno
rykuno
Explore posts from servers
HHono
Created by rykuno on 10/20/2024 in #help
Envs not extendable with `createFactory`
No description
2 replies
DTDrizzle Team
Created by rykuno on 8/26/2023 in #help
Optional/Default value for Relational `Extras`
I have a couple cases where a default/optional value for "extras" in the relational query builder could come in handy. I only really want to run this if the user is logged in. ATM I have the following solution
extras(fields, operators) {
return {
authedUserTicketId:
sql<string>`(SELECT (ticket_id) from ${members} where event_id = ${
fields.id
} and user_id = ${authedUser?.user.id || null})`.as(
'authed_user_membership'
)
};
},
extras(fields, operators) {
return {
authedUserTicketId:
sql<string>`(SELECT (ticket_id) from ${members} where event_id = ${
fields.id
} and user_id = ${authedUser?.user.id || null})`.as(
'authed_user_membership'
)
};
},
If there is no auth user it just sets the user_id to null but its not exactly ideal. Is there any plans or current way to optionally add this statement within the same return block?
9 replies
DTDrizzle Team
Created by rykuno on 7/2/2023 in #help
PGEnum -> Typescript Enum
Hey there. Is there any convenient way people have found to conveniently turn a pgEnum into a typescript enum such as below? Currently I'm creating DTO's but i figured coupling them would be much easier :). I figure ZOD might come into play but we are utilizing NestJS w/ class-validator atm.
const typeEnum = pgEnum('type', [
'short_text',
'long_text',
'single_choice',
'multiple_choice',
]);

export enum SurveyQuestionType {
SHORT_TEXT = 'short_text',
LONG_TEXT = 'long_text',
SINGLE_CHOICE = 'single_choice',
MULTIPLE_CHOICE = 'multiple_choice',
}
const typeEnum = pgEnum('type', [
'short_text',
'long_text',
'single_choice',
'multiple_choice',
]);

export enum SurveyQuestionType {
SHORT_TEXT = 'short_text',
LONG_TEXT = 'long_text',
SINGLE_CHOICE = 'single_choice',
MULTIPLE_CHOICE = 'multiple_choice',
}
5 replies
DTDrizzle Team
Created by rykuno on 5/28/2023 in #help
Relation Query - Get likes in post
Playing around with relational queries and I'm not quite getting how I'd retrieve the count of likes on a given post. I'm able to accomplish this in sql, but I'm having a hard time translating or failing to understand why i cant translate this to drizzle.
const postResults = await db.query.posts.findMany({
where: eq(posts.eventId, params.id),
with: {
author: true,
likes: true
},
orderBy: desc(posts.createdAt)
});
const postResults = await db.query.posts.findMany({
where: eq(posts.eventId, params.id),
with: {
author: true,
likes: true
},
orderBy: desc(posts.createdAt)
});
export const likes = mysqlTable(
"likes",
{
id: cuid2("id").primaryKey().notNull(),
postId: cuid2("post_id").notNull(),
userId: cuid2("user_id").notNull(),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedat: timestamp("updated_at").notNull().defaultNow().onUpdateNow()
},
like => ({
postUserIndex: uniqueIndex("likes__post_id__user_id__idx").on(
like.postId,
like.userId
),
postIndex: index("likes__post_id").on(like.postId)
})
);

export const posts = mysqlTable("posts", {
id: cuid2("id").primaryKey().notNull(),
text: varchar("text", { length: 750 }).notNull(),
authorId: cuid2("author_id").notNull(),
eventId: cuid2("event_id").notNull(),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow().onUpdateNow()
});

export const likesRelations = relations(likes, ({ one }) => ({
post: one(posts, {
fields: [likes.postId],
references: [posts.id]
}),
user: one(users, {
fields: [likes.userId],
references: [users.id]
})
}));

export const postsRelations = relations(posts, ({ one, many }) => ({
author: one(users, {
fields: [posts.authorId],
references: [users.id]
}),
event: one(events, {
fields: [posts.eventId],
references: [events.id]
}),
likes: many(likes)
}));
export const likes = mysqlTable(
"likes",
{
id: cuid2("id").primaryKey().notNull(),
postId: cuid2("post_id").notNull(),
userId: cuid2("user_id").notNull(),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedat: timestamp("updated_at").notNull().defaultNow().onUpdateNow()
},
like => ({
postUserIndex: uniqueIndex("likes__post_id__user_id__idx").on(
like.postId,
like.userId
),
postIndex: index("likes__post_id").on(like.postId)
})
);

export const posts = mysqlTable("posts", {
id: cuid2("id").primaryKey().notNull(),
text: varchar("text", { length: 750 }).notNull(),
authorId: cuid2("author_id").notNull(),
eventId: cuid2("event_id").notNull(),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow().onUpdateNow()
});

export const likesRelations = relations(likes, ({ one }) => ({
post: one(posts, {
fields: [likes.postId],
references: [posts.id]
}),
user: one(users, {
fields: [likes.userId],
references: [users.id]
})
}));

export const postsRelations = relations(posts, ({ one, many }) => ({
author: one(users, {
fields: [posts.authorId],
references: [users.id]
}),
event: one(events, {
fields: [posts.eventId],
references: [events.id]
}),
likes: many(likes)
}));
7 replies
DTDrizzle Team
Created by rykuno on 5/13/2023 in #help
Custom `Select` object returns type `any`
Databases like Planetscale do not support FK constraints. As I understand I can manipulate the returned data structure from within the select clause. The data structure returned is correct but there is a typescript error casting it to any. Is there a way to fix this or am I misusing select?
const [event] = await db
.select({
...events,
createdBy: {
...users
}
})
.from(events)
.innerJoin(users, eq(events.createdByUserId, users.id))
.where(eq(events.id, params.id));
const [event] = await db
.select({
...events,
createdBy: {
...users
}
})
.from(events)
.innerJoin(users, eq(events.createdByUserId, users.id))
.where(eq(events.id, params.id));
export const events = mysqlTable("events", {
id: cuid2("id").primaryKey().notNull(),
name: text("name").notNull(),
description: text("description"),
image: text("image").notNull(),
privacy: text("privacy", { enum: ["public", "private"] }).notNull(),
startDate: timestamp("startDate").notNull(),
endDate: timestamp("endDate").notNull(),
createdByUserId: cuid2("created_by_user_id").notNull(),
created_at: timestamp("created_at").notNull().defaultNow(),
updated_at: timestamp("updated_at").notNull().defaultNow().onUpdateNow()
});
export const events = mysqlTable("events", {
id: cuid2("id").primaryKey().notNull(),
name: text("name").notNull(),
description: text("description"),
image: text("image").notNull(),
privacy: text("privacy", { enum: ["public", "private"] }).notNull(),
startDate: timestamp("startDate").notNull(),
endDate: timestamp("endDate").notNull(),
createdByUserId: cuid2("created_by_user_id").notNull(),
created_at: timestamp("created_at").notNull().defaultNow(),
updated_at: timestamp("updated_at").notNull().defaultNow().onUpdateNow()
});
1 replies
TTCTheo's Typesafe Cult
Created by rykuno on 5/7/2023 in #questions
Next-Auth Session in Server Function
Trying out the new app directory with an example project and ran into issues with accessing the user session within a server function via getServerSession
"use server";

import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import prisma from "@/db";
import { EventPrivacy } from "@prisma/client";
import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";

export async function createEvent(formData: FormData) {
const session = await getServerSession(authOptions);
if (!session) return;

const event = await prisma.event.create({
data: {
image: formData.get("imageUrl") as string,
name: formData.get("name") as string,
description: formData.get("description") as string,
startDate: new Date(formData.get("startDate") as string),
endDate: new Date(formData.get("endDate") as string),
privacy: formData.get("privacy") as EventPrivacy,
createdById: session.user.id
}
});
redirect(`/event/${event.id}`);
}
"use server";

import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import prisma from "@/db";
import { EventPrivacy } from "@prisma/client";
import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";

export async function createEvent(formData: FormData) {
const session = await getServerSession(authOptions);
if (!session) return;

const event = await prisma.event.create({
data: {
image: formData.get("imageUrl") as string,
name: formData.get("name") as string,
description: formData.get("description") as string,
startDate: new Date(formData.get("startDate") as string),
endDate: new Date(formData.get("endDate") as string),
privacy: formData.get("privacy") as EventPrivacy,
createdById: session.user.id
}
});
redirect(`/event/${event.id}`);
}
Calling this code from an action handler within a form yields the following error Method expects to have requestAsyncStorage, none available. Is there anyone who has successfully gotten this to work?
29 replies
TTCTheo's Typesafe Cult
Created by rykuno on 1/25/2023 in #questions
Prisma: Asyncronous Extended Fields
Anyone familiar with any better way to accomplish the equivalent of field resolvers with prisma? The Ask I need an async field returned with each user The Scenario Say I want to findMany on users but I want a likeCount and followCount fields returned with each result. The expand api looks to be on the right track but it looks like its unable to perform asynchronous computes for additional fields. Such as if I wanted to add an async field called likeCount to user which would be returned on each user result.
const xprisma = prisma
.$extends({
result: {
user: {
likeCount: {
needs: { id: true },
compute({id}) {
return prisma.likes.count({where: userId: id})
},
},
},
},
})
const xprisma = prisma
.$extends({
result: {
user: {
likeCount: {
needs: { id: true },
compute({id}) {
return prisma.likes.count({where: userId: id})
},
},
},
},
})
I know I can just _count likes on user for this example. This is simplified for an example
1 replies
TTCTheo's Typesafe Cult
Created by rykuno on 1/17/2023 in #questions
Prisma `clientExtensions` Preview Feature Breaks Types
Enabling the clientExtensions preview feature in prisma.schema causes trpc routers to break all typesatefy. Anyone mess with this yet?
4 replies