Commit 41373fad authored by Цой Данил's avatar Цой Данил 💬

Added routes for backend

parent 26a5a882
import express, { Router, Request, Response } from 'express'
import { Request, Response } from 'express';
export class HealthCheckController {
private router: Router
constructor() {
this.router = express.Router()
this.router.get('/', this.checkHealth)
}
public getRouter = (): Router => {
return this.router
}
private checkHealth = (req: Request, res: Response): void => {
res.send('Server is OK')
}
export const healthCheckController = async (req: Request, res: Response) => {
res.status(200).send('Server is ok')
}
\ No newline at end of file
export const healthCheckController = new HealthCheckController()
\ No newline at end of file
import express, { Request, Response, Router } from "express"
import { MessagesService, messagesService } from "../services/messagesService"
import { auth } from "../middlewares/auth"
import IResponse from "../interfaces/IResponse"
import IMessage from "../interfaces/IMessage"
import { EStatuses } from "../enum/EStatuses"
import IModifiedRequest from "../interfaces/IModifiedRequest"
import IMessageDto from "../interfaces/IMessageDto"
export class MessagesController {
private service: MessagesService
private router: Router
constructor(){
this.service = messagesService
this.router = express.Router()
this.router.get('/', auth, this.getMessages)
this.router.post('/', auth, this.addMessage)
}
public getRouter = () => {
return this.router
}
private getMessages = async (req: Request, res: Response): Promise<void> => {
const response: IResponse<IMessage[] | null> = await this.service.getMessages()
if (response.status === EStatuses.SUCCESS){
res.status(200).send(response)
} else{
res.status(418).send(response)
}
}
private addMessage = async (req: Request, res: Response): Promise<void> => {
const modifiedReq = req as IModifiedRequest
if (typeof modifiedReq.verifiedData === 'object'){
const {message} = req.body
const {_id} = modifiedReq.verifiedData
const messageDto: IMessageDto = {
user: _id,
message: message
}
const response: IResponse<IMessage | null> = await this.service.addMessage(messageDto)
if (response.status === EStatuses.SUCCESS){
res.status(200).send(response)
} else{
res.status(418).send(response)
}
} else{
res.status(418).send('error in request. Some invalid field appeared')
}
}
}
export const messagesController = new MessagesController()
\ No newline at end of file
// import express, { Request, Response, Router } from "express"
// import { MessagesService, messagesService } from "../services/messagesService"
// import { auth } from "../middlewares/auth"
// import IResponse from "../interfaces/IResponse"
// import IMessage from "../interfaces/IMessage"
// import { EStatuses } from "../enum/EStatuses"
// import IModifiedRequest from "../interfaces/IModifiedRequest"
// import IMessageDto from "../interfaces/IMessageDto"
// export class MessagesController {
// private service: MessagesService
// private router: Router
// constructor(){
// this.service = messagesService
// this.router = express.Router()
// this.router.get('/', auth, this.getMessages)
// this.router.post('/', auth, this.addMessage)
// }
// public getRouter = () => {
// return this.router
// }
// private getMessages = async (req: Request, res: Response): Promise<void> => {
// const response: IResponse<IMessage[] | null> = await this.service.getMessages()
// if (response.status === EStatuses.SUCCESS){
// res.status(200).send(response)
// } else{
// res.status(418).send(response)
// }
// }
// private addMessage = async (req: Request, res: Response): Promise<void> => {
// const modifiedReq = req as IModifiedRequest
// if (typeof modifiedReq.verifiedData === 'object'){
// const {message} = req.body
// const {_id} = modifiedReq.verifiedData
// const messageDto: IMessageDto = {
// user: _id,
// message: message
// }
// const response: IResponse<IMessage | null> = await this.service.addMessage(messageDto)
// if (response.status === EStatuses.SUCCESS){
// res.status(200).send(response)
// } else{
// res.status(418).send(response)
// }
// } else{
// res.status(418).send('error in request. Some invalid field appeared')
// }
// }
// }
// export const messagesController = new MessagesController()
\ No newline at end of file
import express, { Request, Response, Router } from "express"
import { EStatuses } from "../enum/EStatuses";
import IResponse from "../interfaces/IResponse";
import IUserGetDto from "../interfaces/IUserGetDto";
import { auth } from "../middlewares/auth";
import { usersService, UsersService } from "../services/usersService";
import IModifiedRequest from "../interfaces/IModifiedRequest";
import { Request, Response } from 'express';
import IResponse from '../interfaces/IResponse';
import { EStatuses } from '../enum/EStatuses';
import IUserGetDto from '../interfaces/IUserGetDto';
import { User } from '../models/User';
import { generateJWT } from '../helpers/generateJWT';
import IModifiedRequest from '../interfaces/IModifiedRequest';
import IUserCreateDto from '../interfaces/IUserCreateDto';
export class UsersController {
private service: UsersService
private router: Router
constructor(){
this.service = usersService
this.router = express.Router()
this.router.post('/', this.createUser)
this.router.post('/sessions', this.loginUser)
this.router.get('/token', auth, this.checkToken)
export const createUser = async(req: Request, res: Response) => {
try{
const userDto: IUserGetDto = req.body
const user = new User(userDto)
await user.save()
const responseData: IUserGetDto = {
_id: user._id,
username: user.username,
token: generateJWT({_id: user._id, username: user.username})
}
public getRouter = () => {
return this.router
const response: IResponse<IUserGetDto> = {
status: EStatuses.SUCCESS,
result: responseData,
message: 'User added'
}
private createUser = async (req: Request, res: Response): Promise<void> => {
const response: IResponse<IUserGetDto | null> = await this.service.createUser(req.body)
res.status(200).send(response)
} catch(err: unknown){
const error = err as Error
const response: IResponse<null> = {
status: EStatuses.FAILURE,
result: null,
message: error.message
}
res.status(418).send(response)
}
}
public loginUser = async(req: Request, res: Response): Promise<void> => {
const response: IResponse<IUserGetDto | null> = await this.service.loginUser(req.body)
export const loginUser = async(req: Request, res: Response): Promise<void> => {
try{
const userDto: IUserCreateDto = req.body
const user = await User.findOne({username: userDto.username})
if (!user) throw new Error('User not found')
const isMatch: boolean = await user.checkPassword(userDto.password)
if (!isMatch) throw new Error('Wrong password')
await user.save()
const responseData = {
_id: user._id,
username: user.username,
token: generateJWT({_id: user._id, username: user.username})
}
const response: IResponse<IUserGetDto> = {
status: EStatuses.SUCCESS,
result: responseData,
message: 'Access granted'
}
res.status(200).send(response)
} catch(err: unknown){
const error = err as Error
const response: IResponse<null> = {
status: EStatuses.FAILURE,
result: null,
message: error.message
}
res.status(418).send(response)
}
}
public checkToken = async (expressReq: Request, res: Response): Promise<void> => {
const req = expressReq as IModifiedRequest
export const checkToken = async (req: Request, res: Response): Promise<void> => {
const modifiedReq = req as IModifiedRequest
const response: IResponse<IUserGetDto | null> = {
status: EStatuses.SUCCESS,
result: req.verifiedData as IUserGetDto,
result: modifiedReq.verifiedData as IUserGetDto,
message: 'Token is ok'
}
res.status(200).send(response)
}
}
export const usersController = new UsersController()
\ No newline at end of file
import express, { Express } from "express";
import dotenv from 'dotenv';
import mongoose from 'mongoose';
import express, {Express} from "express";
import cors from 'cors';
import { healthCheckController } from "./controllers/healthCheck";
import { mongooseDB } from "./repository/mongooseDB";
import { usersController } from "./controllers/usersController";
import { messagesController } from "./controllers/messagesController";
import expressWs from "express-ws";
import usersRouter from './routes/usersRoute';
import dotenv from 'dotenv'
import healthCheckRouter from './routes/healthCheckRouter';
dotenv.config()
class App {
private app: Express
constructor() {
this.app = express()
expressWs(this.app)
this.app.use(express.json())
this.app.use(cors())
}
const app: Express = express()
app.use(cors())
app.use(express.json())
app.use('/health-check', healthCheckRouter)
app.use('/users', usersRouter)
public init = async(): Promise<void> => {
const run = async(): Promise<void> => {
try{
this.app.use('/health-check', healthCheckController.getRouter())
this.app.use('/users', usersController.getRouter())
this.app.use('/messages', messagesController.getRouter())
this.app.listen(process.env.APP_PORT, () => {
console.log(`Server is running on http://localhost:${process.env.APP_PORT}`)
mongoose.connect(process.env.MONGO_CLIENT_URL || 'mongodb://localhost/TsoyDanilChatDB')
app.listen(process.env.APP_PORT, () => {
console.log(`Server started at http://localhost:${process.env.APP_PORT}`);
})
await mongooseDB.init()
process.on('exit', () => {
mongooseDB.close()
mongoose.disconnect()
})
} catch(err: unknown){
console.log(err);
}
}
}
const app = new App();
app.init();
\ No newline at end of file
run()
\ No newline at end of file
import express, { Router } from 'express';
import { healthCheckController } from '../controllers/healthCheck';
const healthCheckRouter: Router = express.Router()
healthCheckRouter.get('/', healthCheckController)
export default healthCheckRouter
\ No newline at end of file
import express, { Router } from "express";
import expressWs from "express-ws";
import shortid from "shortid";
import { User } from "../models/User";
import { Message } from "../models/Message";
const messagesRouter: any = express.Router()
expressWs(messagesRouter)
const activeConnections: any= {};
const users: any[] = [];
messagesRouter.ws('/', (ws: any, req: any) => {
const id = shortid.generate()
console.log(`Client connected id=${id}`);
activeConnections[id] = ws
ws.on('close', async (msg: any) => {
console.log(`Client disconnected id = ${id}`);
delete activeConnections[id];
})
ws.on('message', async (msg: any) => {
const decodedMessage = JSON.parse(msg);
switch (decodedMessage.type) {
case 'OPEN_CHAT':
const onlineUser = await User.find({_id: decodedMessage.user._id});
users.push(onlineUser[0]);
Object.keys(activeConnections).forEach(connId => {
const conn = activeConnections[connId];
conn.send(JSON.stringify({
type: "OPEN_CHAT_USER",
user: users
}));
});
break;
case 'CLOSED_CHAT':
const offlineUser = await User.find({_id: decodedMessage.user._id});
Object.keys(activeConnections).forEach(connId => {
const conn = activeConnections[connId];
conn.send(JSON.stringify({
type: "CLOSED_CHAT_USER",
id: offlineUser[0]._id
}));
});
break;
case 'CREATE_MESSAGE':
const message = new Message({user: decodedMessage.user.id, message: decodedMessage.user.text});
await message.save();
const user = await User.findOne({_id: decodedMessage.user.id});
// @ts-ignore
const newMessage = {...message._doc, user: user.username};
Object.keys(activeConnections).forEach(connId => {
const conn = activeConnections[connId];
conn.send(JSON.stringify({
type: "NEW_MESSAGES",
message: newMessage
}));
});
break;
case 'GET_ALL_MESSAGES':
const AllMessages = await Message.find().sort([['datetime', -1]]).populate('user');
Object.keys(activeConnections).forEach(connId => {
const conn = activeConnections[connId];
conn.send(JSON.stringify({
type: "ALL_MESSAGES",
allMessages: AllMessages
}));
});
break;
default:
break;
}
})
})
\ No newline at end of file
import express, { Router } from 'express';
import { checkToken, createUser, loginUser } from '../controllers/usersController';
import { auth } from '../middlewares/auth';
const usersRouter: Router = express.Router();
usersRouter.post('/', createUser)
usersRouter.post('/sessions', loginUser)
usersRouter.get('/token', auth, checkToken)
export default usersRouter
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment