Skip to content

Commit

Permalink
feat: add user routes, controllers and model
Browse files Browse the repository at this point in the history
  • Loading branch information
hariscs committed Feb 25, 2024
1 parent fdffe0e commit 7462fdb
Show file tree
Hide file tree
Showing 12 changed files with 185 additions and 43 deletions.
3 changes: 1 addition & 2 deletions apps/api/config/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ import { log } from '@repo/logger'

export const connect_db = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI as string)
log(`MongoDB Connected: ${conn.connection.name}`)
await mongoose.connect(process.env.MONGO_URI as string)
} catch (error) {
log(`Error: ${error}`)
process.exit(1)
Expand Down
115 changes: 115 additions & 0 deletions apps/api/src/controllers/user_controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { Request, Response } from 'express'
import { USER_SCHEMA } from '@/models/user_model'
import { isValidObjectId } from 'mongoose'
import { log } from 'console'

//* @desc Post user
//* route POST /api/user
//? @access Public
export async function post_user(req: Request, res: Response): Promise<void> {
try {
const user_data = req.body

// check if user email already exists
const { email } = req.body
const existing_user = await USER_SCHEMA.findOne({ email })
if (existing_user) {
res.status(409).json({ error: 'User email already exists' })
return
}

//* post user
const new_job = await USER_SCHEMA.create(user_data)
res.status(201).json(new_job)
} catch (error) {
log('Error posting user:', error)
res.status(500).json({ error: 'Internal server error' })
}
}

//* @desc Get user
//* route GET /api/user/:id
//! @access Private
export async function get_user(req: Request, res: Response): Promise<void> {
try {
const { id } = req.params
//* check if id is valid
if (!isValidObjectId(id)) {
res.status(400).json({ error: 'Invalid id' })
return
}
//* check if user exists
const user = await USER_SCHEMA.findById(id)
if (!user) {
res.status(404).json({ error: 'user not found' })
return
}
res.status(200).json(user)
} catch (error) {
log('Error fetching user:', error)
res.status(500).json({ error: 'Internal server error' })
}
}

//* @desc Delete job
//* route DELETE /api/user/:id
//! @access Private
export async function delete_user(req: Request, res: Response): Promise<void> {
try {
const { id } = req.params
//* check if id is valid
if (!isValidObjectId(id)) {
res.status(400).json({ error: 'Invalid id' })
return
}
//* check if user exists
const user = await USER_SCHEMA.findById(id)
if (!user) {
res.status(404).json({ error: 'user not found' })
return
}
//* delete user
await USER_SCHEMA.findByIdAndDelete(id)
res.status(200).json({ message: 'user deleted successfully' })
} catch (error) {
log('Error deleting user:', error)
res.status(500).json({ error: 'Internal server error' })
}
}

//* @desc Update user
//* route PATCH /api/user/:id
//! @access Private
export async function update_user(req: Request, res: Response): Promise<void> {
try {
const { id } = req.params
//* check if id is valid
if (!isValidObjectId(id)) {
res.status(400).json({ error: 'Invalid id' })
return
}
//* check if user exists
const user = await USER_SCHEMA.findById(id)
if (!user) {
res.status(404).json({ error: 'user not found' })
return
}

// check if user email already exists
const { email } = req.body
const existing_user = await USER_SCHEMA.findOne({ email })
if (existing_user && existing_user._id.toString() !== id) {
res.status(400).json({ error: 'Email already exists' })
return
}

//* update user
const updated_user = await USER_SCHEMA.findByIdAndUpdate(id, req.body, {
new: true,
})
res.status(200).json(updated_user)
} catch (error) {
log('Error updating user:', error)
res.status(500).json({ error: 'Internal server error' })
}
}
16 changes: 12 additions & 4 deletions apps/api/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
import { log } from '@repo/logger'
import { createServer } from './server'
import job_route from '@/routes/job_route'
import { job_route, user_route } from '@/routes'
import { connect_db } from 'config/db'

const port = process.env.PORT || 5001
const server = createServer()

server.use('/api/v1/jobs', job_route)
server.use('/api/v1/user', user_route)

server.listen(port, () => {
log(`api running on ${port}`)
})
connect_db()
.then(() => {
server.listen(port, () => {
log(`db connected & api running on ${port}`)
})
})
.catch((error) => {
log('Error connecting to db:', error)
})
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Request, Response, NextFunction } from 'express'
import { z } from 'zod'

export function validate_job_data(schema: z.AnyZodObject) {
export function validate_schema(schema: z.AnyZodObject) {
return (req: Request, res: Response, next: NextFunction) => {
try {
schema.parse(req.body)
Expand Down
14 changes: 14 additions & 0 deletions apps/api/src/models/user_model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import mongoose, { Schema } from 'mongoose'

const user_schema = new Schema(
{
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
},
{
timestamps: true,
}
)

export const USER_SCHEMA = mongoose.model('User', user_schema)
2 changes: 2 additions & 0 deletions apps/api/src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { default as job_route } from './job_route'
export { default as user_route } from './user_route'
11 changes: 5 additions & 6 deletions apps/api/src/routes/job_route.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import express from 'express'
const router = express.Router()
import { validate_schema } from '@/middleware/validation_middleware'
import { JOB_VALIDATION_SCHEMA } from '@/validations/job_validation'
import {
delete_job,
get_job,
get_jobs,
post_job,
update_job,
} from '@/controllers/job_controller'
import { validate_job_data } from '@/middleware/job_validation_middleware'
import { JOB_VALIDATION_SCHEMA } from '@/validations/job_validation'

const router = express.Router()

//* @desc Get all jobs
//? @access Public
Expand All @@ -21,14 +20,14 @@ router.get('/:id', get_job)

//* @desc Post job
//! @access Private
router.post('/', validate_job_data(JOB_VALIDATION_SCHEMA), post_job)
router.post('/', validate_schema(JOB_VALIDATION_SCHEMA), post_job)

//* @desc Delete job
//! @access Private
router.delete('/:id', delete_job)

//* @desc Update job
//! @access Private
router.patch('/:id', validate_job_data(JOB_VALIDATION_SCHEMA), update_job)
router.patch('/:id', validate_schema(JOB_VALIDATION_SCHEMA), update_job)

export default router
28 changes: 28 additions & 0 deletions apps/api/src/routes/user_route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import express from 'express'
const router = express.Router()
import { validate_schema } from '@/middleware/validation_middleware'
import { USER_VALIDATION_SCHEMA } from '@/validations/user_validation'
import {
delete_user,
get_user,
post_user,
update_user,
} from '@/controllers/user_controller'

//* @desc Post user
//? @access Public
router.post('/', validate_schema(USER_VALIDATION_SCHEMA), post_user)

//* @desc Get user
//! @access Private
router.get('/:id', get_user)

//* @desc Delete user
//! @access Private
router.delete('/:id', delete_user)

//* @desc Update user
//! @access Private
router.patch('/:id', validate_schema(USER_VALIDATION_SCHEMA), update_user)

export default router
2 changes: 0 additions & 2 deletions apps/api/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@ import express, { type Express } from 'express'
import morgan from 'morgan'
import cors from 'cors'
import { config } from 'dotenv'
import { connect_db } from 'config/db'

config()
connect_db()

export const createServer = (): Express => {
const app = express()
Expand Down
7 changes: 7 additions & 0 deletions apps/api/src/validations/user_validation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { z } from 'zod'

export const USER_VALIDATION_SCHEMA = z.object({
name: z.string(),
email: z.string().email(),
password: z.string().min(6),
})
12 changes: 0 additions & 12 deletions apps/api/types/index.ts

This file was deleted.

16 changes: 0 additions & 16 deletions apps/api/types/package.json

This file was deleted.

0 comments on commit 7462fdb

Please sign in to comment.