import { db } from '../utils/db' import { Grouping, Profile } from '../entities' /** * 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 membershipsForProfileId = await db.get(`/membership/${profileId}`) const validGroupingInstances = [] for (let membership of membershipsForProfileId) { const grouping = new Grouping(membership) if (grouping.isValid()) { // Reformat incoming profile data into Profile entity grouping.profile = new Profile(grouping.profile) validGroupingInstances.push(grouping) } } 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 } } export { fetchMembershipsByProfileId, postMembershipByProfileId }