Untitled

mail@pastecode.io avatar
unknown
javascript
2 months ago
2.5 kB
3
Indexable
Never
static async edit(req, res) {
        const { hireflixId, name, email, location, employmentType, tools, questions, description, verrified } = req.body;
        if (!hireflixId || !name || !email || !location || !employmentType || !tools || !questions || !description || !verrified) {
            return res.status(400).json({ message: 'Please fill all data' });
        }
        try {
            //open safe way to connect with db
            const result = await sequelize.transaction(async (t) => {

                //create applicant id
                const newApplicant = await Applicants.create({
                    hireflix_id: hireflixId,
                    name,
                    email,
                    location,
                    employment_type: employmentType,
                    description,
                    verrified
                }, { transaction: t });
                //create tools that applicant use
                const toolsData = tools.map(applicantTools => ({
                    toolsId: applicantTools.tools,
                    applicantId: newApplicant.id
                }));
                await applicantTools.bulkCreate(toolsData, { transaction: t });
                //create questions that applicants have
                const questionsData = questions.map(question => ({
                    title: question.title,
                    mediaUrl: question.media ? question.media.url : null,
                    applicantId: newApplicant.id
                }));
                await Question.bulkCreate(questionsData, { transaction: t });
                //create null rating
                await ratings.create({
                    applicantId: newApplicant.id,
                    rating: null,
                    review: null
                }, { transaction: t })
            });

            const applicantWithRelatedData = await Applicants.findOne({
                where: { id: newApplicant.id },
                include: [
                    { model: db.applicantQuestions, as: 'questions' },
                    { model: db.applicantTools, as: 'tools' },
                    { model: db.applicantRatings, as: 'rating' }
                ]
            });
            res.status(200).json({ message: 'success', data: applicantWithRelatedData })
        } catch (error) {
            res.status(400).json({ message: 'Failed to update user', error: error.message });
        }
    }
Leave a Comment