MCPcopy Create free account
hub / github.com/code100x/cms / deleteQuestionHandler

Function deleteQuestionHandler

src/actions/question/index.ts:154–228  ·  view source on GitHub ↗
(
  data: DeleteTypeQuestion,
)

Source from the content-addressed store, hash-verified

152 }
153};
154const deleteQuestionHandler = async (
155 data: DeleteTypeQuestion,
156): Promise<ReturnTypeDelete> => {
157 const session = await getServerSession(authOptions);
158
159 if (!session || !session.user.id) {
160 return { error: 'Unauthorized' };
161 }
162 const userExists = await db.user.findUnique({
163 where: { id: session.user.id },
164 });
165 if (!userExists) {
166 return {
167 error: 'User not found.',
168 };
169 }
170 const { questionId } = data;
171
172 const question = await db.question.findUnique({
173 where: { id: questionId },
174 });
175
176 if (
177 !question ||
178 (question.authorId !== session.user.id && session.user.role !== ROLES.ADMIN)
179 ) {
180 return {
181 error: 'Unauthorized: You can only delete question you have authored',
182 };
183 }
184
185 try {
186 await db.$transaction(async (prisma) => {
187 // Function to recursively delete answers and their responses
188 const deleteAnswers = async (answerId: number) => {
189 const responses = await prisma.answer.findMany({
190 where: { parentId: answerId },
191 });
192
193 for (const response of responses) {
194 await deleteAnswers(response.id); // Recursively delete child responses
195 }
196
197 await prisma.answer.delete({
198 where: { id: answerId },
199 });
200 };
201
202 // Delete all answers (and their responses) associated with the question
203 const answers = await prisma.answer.findMany({
204 where: { questionId },
205 });
206 for (const answer of answers) {
207 await deleteAnswers(answer.id);
208 }
209
210 // Now delete the question itself
211 await prisma.question.delete({

Callers

nothing calls this directly

Calls 1

deleteAnswersFunction · 0.85

Tested by

no test coverage detected