|
| 1 | +// import req and res types for type safety |
1 | 2 | import { Request, Response } from 'express'; |
| 3 | +import { User } from '../models/user_model.ts'; // imports user model created with mongoose |
2 | 4 |
|
3 | | -let users = [ |
4 | | - { id: 1, name: 'Minh', email: '[email protected]' } |
5 | | -]; |
| 5 | +// controller: GET /api/users |
| 6 | +// This function handles GET reqs to /api/users |
| 7 | +// It fetches all users from MongoDB and sends them as json |
6 | 8 |
|
7 | | -export const getUsers = (_req: Request, res: Response) => { |
8 | | - res.json(users); |
| 9 | +export const getUsers = async (_req: Request, res: Response) => { |
| 10 | + try { |
| 11 | + // retrieves all docs from "users" collection |
| 12 | + const users = await User.find().lean(); // .lean() returns plain JS objects instead of Mongoose docs, may change incase we need extra model methods later |
| 13 | + res.json(users); // sends list of users back as JSON response |
| 14 | + } catch (err) { // log the error if something goes wrong |
| 15 | + console.error('GET /api/users error:', err); |
| 16 | + res.status(500).json({ error: 'Failed to fetch users' }); |
| 17 | + } |
9 | 18 | }; |
10 | 19 |
|
11 | | -export const createUser = (req: Request, res: Response) => { |
12 | | - const { name, email } = req.body; |
13 | | - |
14 | | - if (!name || !email) { |
15 | | - return res.status(400).json({ error: 'name and email required' }); |
16 | | - } |
17 | 20 |
|
18 | | - const newUser = { id: users.length + 1, name, email }; |
19 | | - users.push(newUser); |
20 | | - res.status(201).json(newUser); |
| 21 | +// controller: POST /api/users |
| 22 | +// reads data from req body, vailidates it and creates a new user |
| 23 | +export const createUser = async (req: Request, res: Response) => { |
| 24 | + try { |
| 25 | + // Destructure the req body sent by the client |
| 26 | + // The ?? {} ensures we don't get error if req.body is undefined |
| 27 | + const { name, email } = req.body ?? {}; |
| 28 | + |
| 29 | + // Basic validation to ensure both name and email are provided |
| 30 | + // if not respond with bad request and stop further processes |
| 31 | + if (!name || !email) { |
| 32 | + return res.status(400).json({ error: 'name and email required' }); |
| 33 | + } |
| 34 | + |
| 35 | + // create a new user doc in DB using Mongoose's .create() |
| 36 | + const user = await User.create({ name, email }); |
| 37 | + // respond with "created" and send back created user as JSON |
| 38 | + res.status(201).json(user); |
| 39 | + } catch(err: any) { |
| 40 | + // Handle duplicate email error |
| 41 | + // Mongo DB rejects duplicat value since we have email marked as 'unique' |
| 42 | + if (err?.code === 11000) { |
| 43 | + return res.status(409).json({ error: 'email already exists' }); |
| 44 | + } |
| 45 | + |
| 46 | + // for all other errors, log them and return generic 500 response |
| 47 | + console.error('POST /api/users error:', err); |
| 48 | + res.status(500).json({error: 'Failed to create user' }); |
| 49 | + } |
21 | 50 | }; |
0 commit comments