Feature/duplicate surveys (#268)

* add duplicate to menu

* add duplicate survey API endpoint

---------

Co-authored-by: Matthias Nannt <mail@matthiasnannt.com>
This commit is contained in:
Johannes
2023-05-02 15:33:45 +02:00
committed by GitHub
parent a0acc945b2
commit 478d4e16f8
4 changed files with 117 additions and 4 deletions
@@ -0,0 +1,71 @@
import { hasEnvironmentAccess } from "@/lib/api/apiHelper";
import { prisma } from "@formbricks/database";
import type { NextApiRequest, NextApiResponse } from "next";
export default async function handle(req: NextApiRequest, res: NextApiResponse) {
const environmentId = req.query.environmentId?.toString();
const surveyId = req.query.surveyId?.toString();
if (environmentId === undefined) {
return res.status(400).json({ message: "Missing environmentId" });
}
if (surveyId === undefined) {
return res.status(400).json({ message: "Missing surveyId" });
}
const hasAccess = await hasEnvironmentAccess(req, res, environmentId);
if (!hasAccess) {
return res.status(403).json({ message: "Not authorized" });
}
// POST
else if (req.method === "POST") {
// duplicate current survey including its triggers
const existingSurvey = await prisma.survey.findFirst({
where: {
id: surveyId,
environmentId,
},
include: {
triggers: true,
},
});
if (!existingSurvey) {
return res.status(404).json({ message: "Survey not found" });
}
// create new survey with the data of the existing survey
const newSurvey = await prisma.survey.create({
data: {
...existingSurvey,
id: undefined, // id is auto-generated
environmentId: undefined, // environmentId is set below
name: `${existingSurvey.name} (copy)`,
createdAt: new Date(),
updatedAt: new Date(),
status: "draft",
questions: JSON.parse(JSON.stringify(existingSurvey.questions)),
thankYouCard: JSON.parse(JSON.stringify(existingSurvey.thankYouCard)),
triggers: {
create: existingSurvey.triggers.map((trigger) => ({
eventClassId: trigger.eventClassId,
})),
},
environment: {
connect: {
id: environmentId,
},
},
},
});
return res.json(newSurvey);
}
// Unknown HTTP Method
else {
throw new Error(`The HTTP ${req.method} method is not supported by this route.`);
}
}