'use strict' ; import { Router , RequestHandler , Request , Response , NextFunction } from 'express' ; import { setupMetaverseAPI , finishMetaverseAPI } from '@Route-Tools/middleware' ; import { accountFromAuthToken , param1FromParams } from '@Route-Tools/middleware' ; import { Accounts } from '@Entities/Accounts' ; import { PaginationInfo } from '@Entities/EntityFilters/PaginationInfo' ; import { SArray , VKeyedCollection } from '@Tools/vTypes' ; import { IsNullOrEmpty , IsNotNullOrEmpty } from '@Tools/Misc' ; const procGetUserFriends = async ( req , resp , next ) => { if ( req . vAuthAccount ) { const pager = new PaginationInfo ( ) ; pager . parametersFromRequest ( req ) ; let friends = await Accounts . getField ( req . vAuthToken , req . vAuthAccount , 'friends' , req . vAuthAccount ) ; friends = IsNullOrEmpty ( friends ) ? [ ] : friends ; req . vRestResp . Data = { 'friends' : friends } ; pager . addResponseFields ( req ) ; } else { req . vRestResp . respondFailure ( req . vAccountError ?? 'Not logged in' ) ; } ; next ( ) ; } ; const procPostUserFriends = async ( req , resp , next ) => { if ( req . vAuthAccount ) { if ( req . body . username && typeof ( req . body . username ) === 'string' ) { const newFriend = req . body . username ; const connections = await Accounts . getField ( req . vAuthToken , req . vAuthAccount , 'connections' , req . vAuthAccount ) ?? [ ] ; if ( SArray . hasNoCase ( connections , newFriend ) ) { const updates = { } ; await Accounts . setField ( req . vAuthToken , req . vAuthAccount , 'friends' , { "add" : newFriend } , req . vAuthAccount , updates ) ; await Accounts . updateEntityFields ( req . vAuthAccount , updates ) ; } else { req . vRestResp . respondFailure ( 'cannot add friend who is not a connection' ) ; } ; } else { req . vRestResp . respondFailure ( 'badly formed request' ) ; } ; } else { req . vRestResp . respondFailure ( req . vAccountError ?? 'Not logged in' ) ; } ; next ( ) ; } ; const procDeleteUserFriends = async ( req , resp , next ) => { if ( req . vAuthAccount ) { await Accounts . removeFriend ( req . vAuthAccount , req . vParam1 ) ; } else { req . vRestResp . respondFailure ( req . vAccountError ?? 'Not logged in' ) ; } ; next ( ) ; } ; export const name = '/api/v1/user/friends' ; export const router = Router ( ) ; router . get ( '/api/v1/user/friends' , [ setupMetaverseAPI , accountFromAuthToken , procGetUserFriends , finishMetaverseAPI ] ) ; router . post ( '/api/v1/user/friends' , [ setupMetaverseAPI , accountFromAuthToken , procPostUserFriends , finishMetaverseAPI ] ) ; router . delete ( '/api/v1/user/friends/:param1' , [ setupMetaverseAPI , accountFromAuthToken , param1FromParams , procDeleteUserFriends , finishMetaverseAPI ] ) ;