import { Survey } from '../entities/index.js' import { fetchQuestions } from '../services/index.js' import { possible } from './lang.js' const promptToComponent = { email: 'FormInput', name: 'FormInput', seeking: 'FormDropdown', urgency: 'FormDropdown', presence: 'FormDropdown', duration: 'FormDropdown', experience: 'FormTags', pronouns: 'FormDropdown', language: 'FormDropdown', image: 'FormInput', distance: 'FormInput', zipcode: 'FormInput', blurb: 'FormInput', aspects: 'Aspects' } /** * Make a step from match or step information * @param {object} match * @param {object} step * @returns something like a response_key with possible responses */ const formatStep = (match, step) => { const responsesByCategory = possible['usa'] const responseKey = { response_key_id: match ? match.response_key_id : null, response_key_category: match ? match.response_key_category : 'profile', response_key_prompt: match ? match.response_key_prompt : step, response_key_description: match ? match.response_key_description : null, } return { ...responseKey, responses: responsesByCategory[step] ? responsesByCategory[step] : [], } } const associateWithComponent = responseKeyLike => { let component = promptToComponent[responseKeyLike.response_key_prompt] return { ...responseKeyLike, component } } const hasMatch = (step, inArray) => { return inArray.find(q => q.response_key_prompt == step) } class SurveyFactory { constructor() { this.questionsFromDb = [] } _setSteps(langFile) { const stepsToProcess = [...Object.values(langFile)] const seenIds = [] const stepsInCommon = stepsToProcess.map(step => { // Match question to step const match = hasMatch(step, this.questionsFromDb) if (match) { seenIds.push(match.response_key_id) } const responseKeyLike = formatStep(match, step) const withComponent = associateWithComponent(responseKeyLike) console.log('withComponent :>> ', withComponent) return withComponent }) const unseen = this.questionsFromDb.filter( q => !seenIds.includes(q.response_key_id), ) return [...stepsInCommon, ...unseen] } async getQuestions() { try { this.questionsFromDb = await fetchQuestions() return this.questionsFromDb } catch (err) { console.error(err) } } async createSurvey(langFile, roleTree) { if (!this.questionsFromDb.length) { const res = await this.getQuestions() console.warn( `Attempted to create a survey before getting questions: retrieved ${res.length} questions`, ) } const steps = this._setSteps(langFile) return new Survey(steps, roleTree) } } export { SurveyFactory }