const Schmervice = require('@hapipal/schmervice') module.exports = class ProfileService extends Schmervice.Service { constructor(...args) { super(...args) } /** * Internal method to get list of profile_ids for this user * @param {number} userId * @returns {Array} List of all profile_ids for user */ async _getProfileIdsForUserId(userId) { const { Profile } = this.server.models() /** Grab every Profile associated with this id */ const allProfiles = await Profile.query().where('user_id', userId) /** Copy a list of the just the Profiles */ const profileIdsToGrab = allProfiles.map(profile => profile.profile_id) /** Uncomment to dedupe the list just in case */ return [...new Set(profileIdsToGrab)] } async getCompleteProfilesFor(userId) { const { Profile, Response } = this.server.models() const dedupedProfiles = await this._getProfileIdsForUserId(userId) const responses = await Response.query().whereIn( 'profile_id', dedupedProfiles, ) const profiles = await Profile.query().whereIn( 'profile_id', dedupedProfiles, ) //** Get responses asociated with each profile_id */ return profiles.map(profile => { if (!profile.responses) profile.responses = [] profile.response_keys = [] responses.forEach(response => { if (response.profile_id !== profile.profile_id) return profile.response_keys.push(response.response_key_id) profile.responses.push(response) }) return profile }) } /** * Save responses in a profile * @param {number} userId * @param {Array} responses * @returns */ async saveProfile(userId, responses, txn) { console.warn(userId, responses, txn) } /** * Delete a profile * @param {number} userId * @param {number} profileId * @returns */ async deleteProfile(userId, profileId) { const { Profile } = this.server.models() const dedupedGroupings = await this._getProfileIdsForUserId(userId) /** Do NOTHING if NOT in Grouping */ if (!dedupedGroupings.includes(profileId)) return return await Profile.query().delete().where('profile_id', profileId) } }