Alaskan donut
Alaskan donut
Explore posts from servers
TtRPC
Created by Alaskan donut on 9/16/2024 in #❓-help
How to get pageParam from useInfiniteQuery()?
How would I write a tRPC call equivalent to this traditional useInfiniteQuery? My primary concern here is that I need to pass in a cursor to my procedure, and upon each successive query I need to update this cursor for the next call.
const {
data: posts,
isFetching,
error,
hasNextPage,
fetchNextPage,
} = useInfiniteQuery({
queryKey: ["profile-posts", username],
queryFn: ({ pageParam }) =>
kyInstance
.get(
`/api/profiles/${username}/posts`,
pageParam ? { searchParams: { cursor: pageParam } } : {},
)
.json<TProfilePostsPage>(),
initialPageParam: null as string | null,
getNextPageParam: (lastPage) => lastPage.nextCursor,
});
const {
data: posts,
isFetching,
error,
hasNextPage,
fetchNextPage,
} = useInfiniteQuery({
queryKey: ["profile-posts", username],
queryFn: ({ pageParam }) =>
kyInstance
.get(
`/api/profiles/${username}/posts`,
pageParam ? { searchParams: { cursor: pageParam } } : {},
)
.json<TProfilePostsPage>(),
initialPageParam: null as string | null,
getNextPageParam: (lastPage) => lastPage.nextCursor,
});
Maybe it should be something like this?
const [nextCursor, setNextCursor] = useState<string | null>(null)

const {
data: posts,
isFetching,
error,
hasNextPage,
fetchNextPage,
} = trpc.getProfilePosts.useInfiniteQuery({ username, cursor: nextCursor }, {
queryKey: ["profile-posts", username],
initialPageParam: null as string | null,
getNextPageParam: (lastPage) => {
setNextCursor(lastPage.nextCursor)
return lastPage.nextCursor
},
});
const [nextCursor, setNextCursor] = useState<string | null>(null)

const {
data: posts,
isFetching,
error,
hasNextPage,
fetchNextPage,
} = trpc.getProfilePosts.useInfiniteQuery({ username, cursor: nextCursor }, {
queryKey: ["profile-posts", username],
initialPageParam: null as string | null,
getNextPageParam: (lastPage) => {
setNextCursor(lastPage.nextCursor)
return lastPage.nextCursor
},
});
2 replies
TTCTheo's Typesafe Cult
Created by Alaskan donut on 9/14/2024 in #questions
uploadthing replacing name and adding customId in middleware fails to run
This middleware does not run, despite this being close to what is provided in the documentation for changing file names and adding customIds (https://docs.uploadthing.com/file-routes#middleware). Logging the error provided by useUploadThing()'s onUploadError gives UploadThingError: Failed to run middleware... Caused by: Object { … }
.middleware(async ({ req, files }) => {
// This code runs on your server before upload
const { user } = await validateRequest();

// If you throw, the user will not be able to upload
if (!user) throw new UploadThingError("Unauthorized");

// Override file name and add customId
const fileOverrides = files.map((file) => {
const newName = uniqueNamesGenerator({
dictionaries: [adjectives, animals, colors],
length: 4,
});
const uuid = crypto.randomUUID();
return { ...file, name: newName, customId: uuid };
});

// Whatever is returned here is accessible in onUploadComplete as `metadata`
// Return userId to be used in onUploadComplete
return { userId: user.id, [UTFiles]: fileOverrides };
// return { userId: user.id };
})
.middleware(async ({ req, files }) => {
// This code runs on your server before upload
const { user } = await validateRequest();

// If you throw, the user will not be able to upload
if (!user) throw new UploadThingError("Unauthorized");

// Override file name and add customId
const fileOverrides = files.map((file) => {
const newName = uniqueNamesGenerator({
dictionaries: [adjectives, animals, colors],
length: 4,
});
const uuid = crypto.randomUUID();
return { ...file, name: newName, customId: uuid };
});

// Whatever is returned here is accessible in onUploadComplete as `metadata`
// Return userId to be used in onUploadComplete
return { userId: user.id, [UTFiles]: fileOverrides };
// return { userId: user.id };
})
1 replies
PPrisma
Created by Alaskan donut on 8/28/2024 in #help-and-questions
Complicated groupBy query
Hey there, I am attempting to do something with Prisma that may be undoable. I am still very new to web dev and Prisma, so be aware I don't doubt I'm missing something obvious here. I would like to use post.findMany() to find posts for a specific user, but in this query I would like to include the number of reactions associated with a post for a kind of reactionType. In my project, I am using emoji reactions on posts, and I need to return the number of reactions per emoji type (reactionType). However, I am at a loss for how to do this without many queries per request. Using groupBy() works if I grab the posts first and then use the post.id of each post...
prisma.reaction.groupBy({
by: "reactionTypeId",
where: { postId: { in: postList } },
_count: true,
})
prisma.reaction.groupBy({
by: "reactionTypeId",
where: { postId: { in: postList } },
_count: true,
})
^ This returns the following:
[
{ _count: 1, reactionTypeId: 'U+1FAE0' },
{ _count: 2, reactionTypeId: 'U+2764' }
]
[
{ _count: 1, reactionTypeId: 'U+1FAE0' },
{ _count: 2, reactionTypeId: 'U+2764' }
]
...and then merging the results from this with the original posts list, but this method is fairly complicated and I still haven't solved how to include a boolean value which indicates whether or not the current user has reacted to this post with a given emoji/reactionType... this would require additional queries. I think the ideal structure would be an object called reactionTypes of the following type appended to the post object:
type ReactionType = {
[key: string]: {
id: string,
reacted: boolean
}
}
type ReactionType = {
[key: string]: {
id: string,
reacted: boolean
}
}
... where the key here is the id of the reactionType like "U+2764" which is the unicode for a red heart emoji. Of course, I don't exactly need this format, I just need this data 🙂 (i.e., reacted boolean, count number) If anyone has thought about how I might be best include this reaction data, I would greatly appreciate it. I've been struggling for hours on this. For schema-related details, see the below schema.prisma (comment)
7 replies
PPrisma
Created by Alaskan donut on 6/6/2024 in #help-and-questions
Flat response from relational query?
I am trying to use the following Prisma query to get a post object back containing post details and the username of the user that posted it: const posts = await prisma.post.findMany({ where: { users: { username: { equals: username, mode: "insensitive", }, }, }, select: { contentText: true, users: { select: { username: true, }, }, }, }); This returns [ { contentText: 'Embarking on a thrilling journey in Glacier National Park ⛰️ was an unforgettable experie nce! Amidst stunning landscapes, we had a heart-pounding encounter with a majestic bear, a reminder of the untamed beauty of nature. Days were spent foraging mushrooms 🍄, adding a delicious touch to our lakeside feasts. Nights by the crackling fire on the lakeshore were filled with laughter, storytelling, and a deep sense of camaraderie. Surrounded by towering mountains and the tranquil lake, each moment felt like a cherished memory in the making. With my partner and friends by my side, we immersed ourselves in the serenity of the wilderness, forging bonds that will last a lifetime. 🪄' , users: { username: 'Alaskan' } } ] I would like username to be level with contentText without having to manually flatten the objects returned in this response array. How is this accomplished?
4 replies