From 7debe1703d5573c4bdb2198197a719057d01bad2 Mon Sep 17 00:00:00 2001 From: acatzk Date: Sun, 28 Jan 2024 22:42:15 +0800 Subject: [PATCH] feat(be): implement getUserByUsername api function --- server/api/routers/user.ts | 63 +++++++++++++++++++++++++++++++++++--- 1 file changed, 59 insertions(+), 4 deletions(-) diff --git a/server/api/routers/user.ts b/server/api/routers/user.ts index 2f07c4d..b382699 100644 --- a/server/api/routers/user.ts +++ b/server/api/routers/user.ts @@ -1,11 +1,66 @@ -import { protectedProcedure, createTRPCRouter } from '../trpc' +import { z } from 'zod' + +import { protectedProcedure, createTRPCRouter } from './../trpc' export const userRouter = createTRPCRouter({ - currentUser: protectedProcedure.query(({ ctx }) => { - return ctx.db.user.findUnique({ + currentUser: protectedProcedure.query(async ({ ctx }) => { + return await ctx.db.user.findUniqueOrThrow({ where: { externalId: ctx.auth.userId } }) - }) + }), + + getUserbyUsername: protectedProcedure + .input( + z.object({ + limit: z.number().min(1).max(100).nullish(), + cursor: z.number().nullish(), // <-- "cursor" needs to exist, but can be any type + username: z.string() + }) + ) + .query(async (opts) => { + const { ctx, input } = opts + const limit = input.limit ?? 15 + const { cursor } = input + + const posts = await ctx.db.user.findMany({ + take: limit + 1, // get an extra item at the end which we'll use as next cursor + cursor: cursor ? { id: cursor } : undefined, + where: { + username: input.username + }, + select: { + id: true, + displayName: true, + username: true, + imageUrl: true, + email: true, + posts: { + select: { + id: true, + mediaFiles: { + select: { + url: true + } + } + }, + orderBy: { + createdAt: 'desc' + } + } + } + }) + + let nextCursor: typeof cursor | undefined = undefined + if (posts.length > limit) { + const nextItem = posts.pop() + nextCursor = nextItem!.id + } + + return { + posts, + nextCursor + } + }) })