11import * as Types from '@/types' ;
22import * as Utils from '@/lib/utils' ;
33import * as Schema from './profile.schema' ;
4- import { AppNotFoundError , AppUniqueConstraintViolationError } from '@/lib/app-error' ;
4+ import * as AppError from '@/lib/app-error' ;
55import { Prisma , Profile , User } from '@/../prisma/client' ;
66import db from '@/lib/db' ;
77
@@ -76,7 +76,29 @@ export const getProfileById = async (profileId: Profile['id'], userId: User['id'
7676 } ) ,
7777 ) ;
7878 if ( profile ) return prepareProfileData ( profile , userId ) ;
79- throw new AppNotFoundError ( 'Profile not found' ) ;
79+ throw new AppError . AppNotFoundError ( 'Profile not found' ) ;
80+ } ;
81+
82+ export const getProfileByUsername = async ( username : User [ 'username' ] , userId : User [ 'id' ] ) => {
83+ const profiles = await Utils . handleDBKnownErrors (
84+ db . profile . findMany ( {
85+ ...getExtendedProfileAggregationArgs ( userId ) ,
86+ where : { user : { username } } ,
87+ } ) ,
88+ ) ;
89+ if ( profiles . length === 1 ) return prepareProfileData ( profiles [ 0 ] , userId ) ;
90+ throw new AppError . AppNotFoundError ( 'Profile not found' ) ;
91+ } ;
92+
93+ export const getProfileByIdOrUsername = async ( idOrUsername : string , userId : User [ 'id' ] ) => {
94+ try {
95+ return await getProfileByUsername ( idOrUsername , userId ) ;
96+ } catch ( error ) {
97+ if ( error instanceof AppError . AppNotFoundError ) {
98+ return await getProfileById ( idOrUsername , userId ) ;
99+ }
100+ throw error ;
101+ }
80102} ;
81103
82104export const updateProfileByUserId = async ( userId : User [ 'id' ] , data : Schema . ValidProfile ) => {
@@ -102,7 +124,7 @@ export const createFollowing = async (userId: User['id'], { profileId }: Schema.
102124 } ) ,
103125 ) ;
104126 } catch ( error ) {
105- if ( error instanceof AppUniqueConstraintViolationError ) return ;
127+ if ( error instanceof AppError . AppUniqueConstraintViolationError ) return ;
106128 throw error ;
107129 }
108130} ;
@@ -112,7 +134,7 @@ export const deleteFollowing = async (userId: User['id'], { profileId }: Schema.
112134 await Utils . handleDBKnownErrors (
113135 db . $transaction ( async ( prismaClient ) => {
114136 const currentProfile = await prismaClient . profile . findUnique ( { where : { userId } } ) ;
115- if ( ! currentProfile ) throw new AppNotFoundError ( 'Profile not found' ) ;
137+ if ( ! currentProfile ) throw new AppError . AppNotFoundError ( 'Profile not found' ) ;
116138 await prismaClient . follows . delete ( {
117139 where : { profileId_followerId : { followerId : currentProfile . id , profileId } } ,
118140 } ) ;
0 commit comments