Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: delete entry services refactoring #191

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
179 changes: 41 additions & 138 deletions backend/src/controllers/entry/entry.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
import * as CdGptServices from '../../models/services/CdGpt.js';
import * as EntryServices from '../../models/services/entry/entry.js';
import {
Entry,
EntryAnalysis,
EntryConversation,
Journal,
} from '../../models/index.js';
import { NextFunction, Request, Response } from 'express';
import { ChatMessage } from '../../models/entry/entryConversation.js';
import ExpressError from '../../utils/ExpressError.js';
import mongoose from 'mongoose';
import { Journal } from '../../models/index.js';

/**
* Request body for create and update Entry operations,
Expand All @@ -25,6 +19,10 @@ export interface UpdateEntryRequestBody {
};
}

export interface UpdateChatRequestBody {
messages: ChatMessage[];
}

/**
* Get all entries in a specific journal.
*/
Expand Down Expand Up @@ -138,41 +136,17 @@ export const deleteEntry = async (
next: NextFunction
) => {
const { entryId } = req.params;

// Start a session and transaction for atomicity
const session = await mongoose.startSession();
session.startTransaction();

try {
// Delete the entry
const response = await Entry.findByIdAndDelete(entryId, { session });

if (!response) {
return next(new ExpressError('Entry not found.', 404));
await EntryServices.deleteEntry(entryId);
req.flash('success', 'Successfully deleted entry.');
res.status(200).json({ flash: req.flash() });
} catch (err) {
const errMessage = (err as Error).message;
if (errMessage === 'Entry not found.') {
return next(new ExpressError((err as Error).message, 404));
}

// Delete associated documents
await EntryConversation.deleteMany({ entry: entryId }, { session });
await EntryAnalysis.deleteMany({ entry: entryId }, { session });

// Commit the transaction
await session.commitTransaction();
} catch {
// If an error occurs, abort the transaction
await session.abortTransaction();
return next(
new ExpressError(
'An error occurred while attempting to delete the entry.',
500
)
);
} finally {
// End the session
session.endSession();
return next(new ExpressError('An error occurred while attempting to delete the entry.', 500));
}

req.flash('success', 'Successfully deleted entry.');
res.status(200).json({ flash: req.flash() });
};

/**
Expand Down Expand Up @@ -204,54 +178,31 @@ export const updateEntryAnalysis = async (
) => {
const { entryId, journalId } = req.params;

// Ensure that the journal exists
const journal = await Journal.findById(journalId);
if (!journal) {
return next(new ExpressError('Journal not found.', 404));
}

const entry = await Entry.findById(entryId);

if (!entry) {
return next(new ExpressError('Entry not found.', 404));
}

const entryAnalysis = await EntryAnalysis.findOne({ entry: entryId });
if (!entryAnalysis) {
return next(new ExpressError('Entry not found.', 404));
}
if (!journal.config) {
return next(new ExpressError('Journal config not found.', 404));
}
try {
const analysis = await CdGptServices.getAnalysisContent(
journal.config.toString(),
entry.content
);

// Complete the entry and analysis with the analysis content if available
if (analysis) {
entry.title = analysis.title;
entry.mood = analysis.mood;
entry.tags = analysis.tags;

entryAnalysis.analysis_content = analysis.analysis_content;
const configId = await verifyJournalExists(journalId);

entryAnalysis.save();
entry.save();
try {
const { errMessage, entry, entryAnalysis } = await EntryServices.updateEntryAnalysis(entryId, configId);

if (errMessage) {
req.flash('info', errMessage);
}
req.flash('success', 'Successfully generated a new analysis.');
res
.status(200)
.json({
...entryAnalysis.toObject(),
entry: entry.toObject(),
flash: req.flash(),
});
} catch (updateError) {
// Possible error from failing to find matching documents for entryId
// Setting appropriate error code here
throw new ExpressError((updateError as Error).message, 404);
}
} catch (err) {
req.flash('info', (err as Error).message);
} catch (error) {
return next(error);
}

res
.status(200)
.json({
...entryAnalysis.toObject(),
entry: entry.toObject(),
flash: req.flash(),
});
};

/**
Expand All @@ -277,7 +228,7 @@ export const createEntryConversation = async (
next: NextFunction
) => {
const { entryId, journalId } = req.params;
const messageData = req.body;
const messageData: UpdateChatRequestBody = req.body;

// Create new EntryConversation
try {
Expand Down Expand Up @@ -307,64 +258,16 @@ export const updateEntryConversation = async (
next: NextFunction
) => {
const { chatId, journalId } = req.params;
const messageData = req.body;

// Get the config from the journal
const journal = await Journal.findById(journalId);
if (!journal) {
return next(new ExpressError('Journal not found.', 404));
}

// Get the conversation from the database
const conversation = await EntryConversation.findById(chatId);
if (!conversation) {
return next(new ExpressError('Entry conversation not found.', 404));
}
if (!conversation.messages) {
return next(
new ExpressError('Entry conversation messages not found.', 404)
);
}
const messageData: UpdateChatRequestBody = req.body;

// Get the analysis associated with the entry
const analysis = await EntryAnalysis.findOne({ entry: conversation.entry });
if (!analysis) {
return next(new ExpressError('Entry analysis not found.', 404));
}

if (!journal.config) {
return next(new ExpressError('Journal config not found.', 404));
}
try {
const llmResponse = await CdGptServices.getChatContent(
journal.config.toString(),
analysis.id,
messageData.messages[0].message_content,
conversation.messages
);

// If the chat is not empty, update the llm_response
if (llmResponse) {
messageData.messages[0].llm_response = llmResponse;
}
} catch (err) {
return next(err);
}
const configId = await verifyJournalExists(journalId);

const response = await EntryConversation.findOneAndUpdate(
{ _id: chatId },
{
$push: {
...messageData,
},
},
{ new: true }
);
if (!response) {
return next(new ExpressError('Failed to update entry conversation.', 500));
const response = await EntryServices.updateEntryConversation(chatId, configId, messageData);
res.status(200).json({ ...response.toObject(), flash: req.flash() });
} catch (error) {
return next(error);
}

res.status(200).json({ ...response.toObject(), flash: req.flash() });
};

/**
Expand Down
Loading