From a989166ae39ecb018569172a0f8dbf56a169bcd3 Mon Sep 17 00:00:00 2001
From: Matt Kirby <MattJKirby@outlook.com>
Date: Sat, 15 Apr 2023 01:27:33 +0100
Subject: [PATCH] Added friend datastore

---
 .../src/Datastores/FriendDataStore.ts         | 61 +++++++++++++++++++
 1 file changed, 61 insertions(+)
 create mode 100644 backend-services/friend-service/src/Datastores/FriendDataStore.ts

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 00000000..b185c814
--- /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
-- 
GitLab