import { db } from '../utils/db.js' import { Grouping, Profile } from '../entities/index.js' /** * Get Memberships associated with a single Profile from the database and * create a class from the data and * validate the incoming against the schema * @param {number} profileId * @returns {array} instantiated Profile objects (see: /entites/profile) */ const fetchMembershipsByProfileId = async profileId => { const validGroupingInstances = [] let memberships try { memberships = await db.get(`/membership/${profileId}`) for (let membership of memberships) { const grouping = new Grouping(membership) if (grouping.isValid()) { // Reformat incoming profile data into Profile entity grouping.profile = new Profile(grouping.profile) const targetTags = await db.get( `/profile/${grouping.profile.profile_id}/tags/${grouping.grouping_id}`, ) const profileTags = await db.get( `/profile/${profileId}/tags/${grouping.grouping_id}`, ) grouping.tags = [...targetTags, ...profileTags] grouping._loading.value = false validGroupingInstances.push(grouping) } } } catch (error) { console.error(`[Grouping Service]: ${error}\ngroupings: ${memberships}`) } return validGroupingInstances } /** * Create memberships to a grouping between profileId and targetId * @param {number} profileId * @param {number} targetId * @param {string} groupingType * @returns {object} the created membership */ const postMembershipByProfileId = async ({ profileId, targetId, groupingType = 'match', }) => { const utcDateInSeconds = Date.now() / 1000 const membership = { target_id: targetId, grouping_type: groupingType, grouping_name: `${utcDateInSeconds}_${profileId}_${targetId}`, } const membershipMatch = await db.post( `/membership/${profileId}/join`, membership, ) return { membershipMatch, groupingName: membership.grouping_name } } const revealProfileInfo = async (membershipId, profileId, tagId) => { const revealed = await db.post( `/membership/${membershipId}/reveal?profile=${profileId}&tag=${tagId}`, ) return revealed } export { fetchMembershipsByProfileId, postMembershipByProfileId, revealProfileInfo, }