Skip to content

Commit

Permalink
Refactor main.js to include validateRequest middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
thadeucbr committed Sep 30, 2024
1 parent 3bf5624 commit 5d2151c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ import setupSwagger from './helper/swagger/swagger.config.js';
import gptMiddleware from './middleware/ai/gpt.middleware.js';
import asyncHandler from './middleware/error/asyncHandler.middlware.js';
import errorHandler from './middleware/error/errorHandler.middlware.js';
import validateRequest from './middleware/ai/validateRequest.middleware.js';

const start = async () => {
await startMongoose();

const app = express();

app.use(express.json());
app.use(asyncHandler(validateRequest))
app.use(asyncHandler(gptMiddleware))
app.use(errorHandler)

Expand Down
21 changes: 21 additions & 0 deletions src/middleware/ai/validateRequest.middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import aiService from '../../service/ai/ai.service.js';

const context = 'You are an AI that acts as a middleware for API request validation. You will receive the body, header, query, method, and URL of a request. Your task is to analyze whether all fields in the request adhere to established patterns and are present. If any field is invalid or missing, return an error message in JSON format: { message, statusCode, status }. If it is a creation (POST) or update (PUT) request, you must also check if the schema for that operation exists and is valid using the get_schemas function. If the request is valid and all fields are correct, return a success message in JSON format: { message: "OK", statusCode: "200", status: "OK" }. Important, don’t send ```JSON in the response.';

const validateRequest = async (req, res, next) => {
console.log(`Request Method: ${req.method}, Request URL: ${req.url}`);
console.log(`Request Body: ${JSON.stringify(req.body)}`);
console.log(`Request Query: ${JSON.stringify(req.query)}`);
console.log(`Request Headers: ${JSON.stringify(req.headers)}`);

const response = await aiService({ body: req.body, header: req.headers, query: req.query, method: req.method, url: req.url, firstContext: context });

const { message, statusCode, status } = JSON.parse(response.content);
console.log({ message, statusCode, status });
if (statusCode != 200) {
return res.status(statusCode).json({ status, message });
}
next()
}

export default validateRequest

0 comments on commit 5d2151c

Please sign in to comment.