Skip to content

Commit

Permalink
Improved error handling withing the chatapi
Browse files Browse the repository at this point in the history
  • Loading branch information
Mutugiii committed Dec 22, 2023
1 parent 5640e00 commit 13e29fb
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
8 changes: 6 additions & 2 deletions chatapi/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,25 @@ app.post('/', async (req: any, res: any) => {
try {
const { data, save } = req.body;

if (typeof data !== 'object' || Array.isArray(data) || Object.keys(data).length === 0) {
res.status(400).json({ 'error': 'Bad Request', 'message': 'The "data" field must be a non-empty object' });
}

if (!save) {
const response = await chatNoSave(data.content);
res.status(200).json({
'status': 'Success',
'chat': response
});
} else if (save && data && typeof data === 'object') {
} else if (save) {
const response = await chat(data);
res.status(201).json({
'status': 'Success',
'chat': response?.completionText,
'couchDBResponse': response?.couchSaveResponse
});
} else {
res.status(400).json({ 'error': 'Bad Request', 'message': 'The "data" field must be a non-empty object' });
res.status(400).json({ 'error': 'Bad Request', 'message': 'Error processing "data" object' });
}
} catch (error: any) {
res.status(500).json({ 'error': 'Internal Server Error', 'message': error.message });
Expand Down
4 changes: 4 additions & 0 deletions chatapi/src/services/chat.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export async function chat(data: any): Promise<{
const { content, ...dbData } = data;
const messages: ChatMessage[] = [];

if (!content) {
throw new Error('"data.content" is a required non-empty field');
}

if (dbData._id) {
await retrieveChatHistory(dbData, messages);
} else {
Expand Down

0 comments on commit 13e29fb

Please sign in to comment.