diff --git a/backend-services/friend-service/src/Datastores/FriendDataStore.ts b/backend-services/friend-service/src/Datastores/FriendDataStore.ts new file mode 100644 index 0000000000000000000000000000000000000000..b185c814dba611eb00227e1784bb7e34f7e1667c --- /dev/null +++ b/backend-services/friend-service/src/Datastores/FriendDataStore.ts @@ -0,0 +1,61 @@ +import FriendSchema from '../Database/Schemas/FriendSchema'; +import RequestSchema from '../Database/Schemas/RequestSchema'; +import { Friend } from '../Types/Friend'; +import { DataStore } from './DataStore'; + +/** + * Contains actions pertaining to storing and accessing Friends + */ +class FriendDataStore extends DataStore<any>{ + + /** + * Create a new friend relation between two users. + * @param u1 + * @param u2 + * @returns + */ + public newFriend = async (u1: string, u2: string): Promise<Friend> => { + if(await this.Model.findOne({User1: u1, User2: u2}) !== null || await this.Model.findOne({User1: u2, User2: u1}) !== null){ + throw new Error(`${u1} and ${u2} are already friends!`); + } + + return await this.Model.create({ + User1: u1, + User2: u2 + }); + }; + + /** + * Store action for getting a users friends + * @param itemCount + * @returns + */ + public getFriends = async (userId: string): Promise<{friends1: Friend[], friends2: Friend[]}> => { + const friends1 = await this.Model.find({User1: userId}) + const friends2 = await this.Model.find({User2: userId}) + + return {friends1, friends2} + } + + /** + * Method to removes a friend relation + * @param user1 + * @param user2 + */ + public RemoveFriend = async (user1: string, user2: string): Promise<void> => { + await this.Model.findOneAndDelete({User1: user1, User2: user2}) + await this.Model.findOneAndDelete({User1: user2, User2: user1}) + } + + /** + * Get the friend item by its id. + * @param id + * @returns + */ + public GetFriendByUsers = async (user1: string, user2: string): Promise<Friend | null> => { + const result = await this.Model.findOne({User1: user1, User2: user2}) || await this.Model.findOne({User1: user2, User2: user1}); + return result; + } +} + +export default new FriendDataStore('Friend', FriendSchema) \ No newline at end of file