Skip to content

Commit

Permalink
[Finishes #187354252-implementing-profile-page-settings
Browse files Browse the repository at this point in the history
  • Loading branch information
hatfelicien committed Apr 28, 2024
1 parent 88bc83d commit f771345
Show file tree
Hide file tree
Showing 5 changed files with 179 additions and 6 deletions.
67 changes: 67 additions & 0 deletions src/controllers/profileController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// controllers/userController.ts
import { Request, Response } from 'express';
import User from '../database/models/user';

const getAllUserProfiles = async (req: Request, res: Response): Promise<void> => {
try {
// Find all user profiles
const users = await User.findAll();

// Return all user profiles
res.status(200).json(users);
} catch (error) {
// Handle errors
console.error('Error fetching user profiles:', error);
res.status(500).send('Internal Server Error');
}
};

const getUserProfile = async (req: Request, res: Response): Promise<void> => {
const userId: string = req.params.userId;

try {
// Find the user by ID
const user = await User.findByPk(userId);
if (!user) {
res.status(404).json({ message: 'User not found' });
return;
}

// Return user profile
res.status(200).json({
id: user.id,
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
});
} catch (error) {
// Handle errors
console.error('Error fetching user profile:', error);
res.status(500).send('Internal Server Error');
}
};

const updateUserProfile = async (req: Request, res: Response): Promise<void> => {
const userId: string = req.params.userId;
const newData = req.body;

try {
// Find the user by ID
const user = await User.findByPk(userId);
if (!user) {
res.status(404).json({ message: 'User not found' });
return;
}

// Update user profile data
await user.update(newData);

res.status(200).json({ message: 'User profile updated successfully' });
} catch (error) {
// Handle errors
console.error('Error updating user profile:', error);
res.status(500).send('Internal Server Error');
}
};

export { getUserProfile, updateUserProfile, getAllUserProfiles };
70 changes: 70 additions & 0 deletions src/docs/profileDoc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
Profiles:
name: User Profiles API
description: API for managing user profiles

paths:
/api/profiles/users:
get:
summary: Get all user profiles
description: Retrieve a list of all user profiles
tags:
- Profiles
responses:
'200':
description: A list of user profiles
'500':
description: Internal server error

/api/profiles/users/{userId}:
get:
summary: Get a user profile by ID
description: Retrieve a user profile by its ID
tags:
- Profiles
parameters:
- in: path
name: userId
required: true
description: ID of the user profile to retrieve
schema:
type: string
responses:
'200':
description: The user profile
'404':
description: User not found
'500':
description: Internal server error

put:
summary: Update a user profile
description: Update an existing user profile
tags:
- Profiles
parameters:
- in: path
name: userId
required: true
description: ID of the user profile to update
schema:
type: string
- in: body
name: body
required: true
description: New data for the user profile
schema:
type: object
properties:
firstName:
type: string
lastName:
type: string
email:
type: string
responses:
'200':
description: User profile updated successfully
'404':
description: User not found
'500':
description: Internal server error
3 changes: 3 additions & 0 deletions src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { Router } from 'express';
import userRoute from './userRoute';
import profileRoutes from './profileRoutes';
import authRoute from './authRoute';
import roleRoute from './roleRoute';

const router = Router();

router.use('/users', userRoute);
// Profile routes
router.use('/profiles', profileRoutes);
router.use('/auth', authRoute);
router.use('/roles', roleRoute);

Expand Down
13 changes: 13 additions & 0 deletions src/routes/profileRoutes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// routes/userRoutes.ts
import express from 'express';
import { getAllUserProfiles, getUserProfile, updateUserProfile } from '../controllers/profileController';

const router = express.Router();
router.get('/users/', getAllUserProfiles);
// User profile retrieval endpoint
router.get('/users/:userId/', getUserProfile);

// User profile update endpoint
router.put('/users/:userId/', updateUserProfile);

export default router;
32 changes: 26 additions & 6 deletions src/server.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { Application, Request, Response } from 'express';
// server.ts
import { Application, Request, Response, NextFunction } from 'express';
import dotenv from 'dotenv';
import cors from 'cors';
import express from 'express';
import swaggerUI from 'swagger-ui-express';
import swaggerJsDoc from 'swagger-jsdoc';
import options from './docs/swaggerdocs';
import routes from './routes';
//import { validateCreateProfile, validateUpdateProfile } from './validations/profileValidation';
import profileRoutes from './routes/profileRoutes';
import passport from './config/passport';
import logger, { errorLogger } from './logs/config';
import expressWinston from 'express-winston';
Expand All @@ -23,32 +26,49 @@ const swaggerSpec = swaggerJsDoc(options);
app.use('/api/docs', swaggerUI.serve, swaggerUI.setup(swaggerSpec));

app.use('/api', routes);
app.use('/docs', swaggerUI.serve, swaggerUI.setup(swaggerSpec));

// Logging middleware
app.use(
expressWinston.logger({
winstonInstance: logger,
statusLevels: true,
})
);

app.get('/', (req: Request, res: Response): void => {
logger.error('Testing logger');
res.send('Welcome at Mavericks E-commerce Website Apis');
// Profile routes
app.use('/profiles', profileRoutes);

// Error handling middleware for profile routes
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
console.error(err.stack);
res.status(500).send('Internal Server Error');
});

// Error handling middleware for other routes
app.use(
expressWinston.errorLogger({
winstonInstance: errorLogger,
})
);

// Default route
app.get('/', (req: Request, res: Response): void => {
logger.error('Testing logger');
res.send('Welcome at Mavericks E-commerce Website Apis ');
});

// Route not found handler

app.all('*', (req: Request, res: Response): void => {
res.status(404).json({ message: 'route not found' });
});

databaseConnection();

// Start server
const PORT = process.env.PORT ?? 3000;
app.listen(PORT, () => {
logger.info(`Server is running on port ${PORT}`);
});

// Connect to database
databaseConnection();

0 comments on commit f771345

Please sign in to comment.