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 { export const healthCheckController = async (req: Request, res: Response) => {
private router: Router res.status(200).send('Server is ok')
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')
}
} }
\ 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 express, { Request, Response, Router } from "express"
import IMessage from "../interfaces/IMessage" // import { MessagesService, messagesService } from "../services/messagesService"
import { EStatuses } from "../enum/EStatuses" // import { auth } from "../middlewares/auth"
import IModifiedRequest from "../interfaces/IModifiedRequest" // import IResponse from "../interfaces/IResponse"
import IMessageDto from "../interfaces/IMessageDto" // import IMessage from "../interfaces/IMessage"
// import { EStatuses } from "../enum/EStatuses"
// import IModifiedRequest from "../interfaces/IModifiedRequest"
export class MessagesController { // import IMessageDto from "../interfaces/IMessageDto"
private service: MessagesService
private router: Router // export class MessagesController {
constructor(){ // private service: MessagesService
this.service = messagesService // private router: Router
this.router = express.Router() // constructor(){
this.router.get('/', auth, this.getMessages) // this.service = messagesService
this.router.post('/', auth, this.addMessage) // this.router = express.Router()
} // this.router.get('/', auth, this.getMessages)
// this.router.post('/', auth, this.addMessage)
public getRouter = () => { // }
return this.router
} // 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){ // private getMessages = async (req: Request, res: Response): Promise<void> => {
res.status(200).send(response) // const response: IResponse<IMessage[] | null> = await this.service.getMessages()
} else{ // if (response.status === EStatuses.SUCCESS){
res.status(418).send(response) // 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'){ // private addMessage = async (req: Request, res: Response): Promise<void> => {
const {message} = req.body // const modifiedReq = req as IModifiedRequest
const {_id} = modifiedReq.verifiedData // if (typeof modifiedReq.verifiedData === 'object'){
const messageDto: IMessageDto = { // const {message} = req.body
user: _id, // const {_id} = modifiedReq.verifiedData
message: message // const messageDto: IMessageDto = {
} // user: _id,
const response: IResponse<IMessage | null> = await this.service.addMessage(messageDto) // message: message
if (response.status === EStatuses.SUCCESS){ // }
res.status(200).send(response) // const response: IResponse<IMessage | null> = await this.service.addMessage(messageDto)
} else{ // if (response.status === EStatuses.SUCCESS){
res.status(418).send(response) // res.status(200).send(response)
} // } else{
} else{ // res.status(418).send(response)
res.status(418).send('error in request. Some invalid field appeared') // }
} // } else{
} // res.status(418).send('error in request. Some invalid field appeared')
} // }
// }
export const messagesController = new MessagesController() // }
\ No newline at end of file
// export const messagesController = new MessagesController()
\ No newline at end of file
import express, { Request, Response, Router } from "express" import { Request, Response } from 'express';
import { EStatuses } from "../enum/EStatuses"; import IResponse from '../interfaces/IResponse';
import IResponse from "../interfaces/IResponse"; import { EStatuses } from '../enum/EStatuses';
import IUserGetDto from "../interfaces/IUserGetDto"; import IUserGetDto from '../interfaces/IUserGetDto';
import { auth } from "../middlewares/auth"; import { User } from '../models/User';
import { usersService, UsersService } from "../services/usersService"; import { generateJWT } from '../helpers/generateJWT';
import IModifiedRequest from "../interfaces/IModifiedRequest"; import IModifiedRequest from '../interfaces/IModifiedRequest';
import IUserCreateDto from '../interfaces/IUserCreateDto';
export class UsersController { export const createUser = async(req: Request, res: Response) => {
private service: UsersService try{
private router: Router const userDto: IUserGetDto = req.body
constructor(){ const user = new User(userDto)
this.service = usersService await user.save()
this.router = express.Router() const responseData: IUserGetDto = {
this.router.post('/', this.createUser) _id: user._id,
this.router.post('/sessions', this.loginUser) username: user.username,
this.router.get('/token', auth, this.checkToken) token: generateJWT({_id: user._id, username: user.username})
} }
const response: IResponse<IUserGetDto> = {
public getRouter = () => { status: EStatuses.SUCCESS,
return this.router 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) 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> => { export const loginUser = async(req: Request, res: Response): Promise<void> => {
const response: IResponse<IUserGetDto | null> = await this.service.loginUser(req.body) 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) 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> => { export const checkToken = async (req: Request, res: Response): Promise<void> => {
const req = expressReq as IModifiedRequest const modifiedReq = req as IModifiedRequest
const response: IResponse<IUserGetDto | null> = { const response: IResponse<IUserGetDto | null> = {
status: EStatuses.SUCCESS, status: EStatuses.SUCCESS,
result: req.verifiedData as IUserGetDto, result: modifiedReq.verifiedData as IUserGetDto,
message: 'Token is ok' message: 'Token is ok'
} }
res.status(200).send(response) res.status(200).send(response)
}
} }
export const usersController = new UsersController()
\ No newline at end of file
import express, { Express } from "express"; import mongoose from 'mongoose';
import dotenv from 'dotenv'; import express, {Express} from "express";
import cors from 'cors'; 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 expressWs from "express-ws";
import usersRouter from './routes/usersRoute';
import dotenv from 'dotenv'
import healthCheckRouter from './routes/healthCheckRouter';
dotenv.config() dotenv.config()
class App { const app: Express = express()
private app: Express
constructor() { app.use(cors())
this.app = express() app.use(express.json())
expressWs(this.app) app.use('/health-check', healthCheckRouter)
this.app.use(express.json()) app.use('/users', usersRouter)
this.app.use(cors())
}
public init = async(): Promise<void> => { const run = async(): Promise<void> => {
try{ try{
this.app.use('/health-check', healthCheckController.getRouter()) mongoose.connect(process.env.MONGO_CLIENT_URL || 'mongodb://localhost/TsoyDanilChatDB')
this.app.use('/users', usersController.getRouter()) app.listen(process.env.APP_PORT, () => {
this.app.use('/messages', messagesController.getRouter()) console.log(`Server started at http://localhost:${process.env.APP_PORT}`);
this.app.listen(process.env.APP_PORT, () => {
console.log(`Server is running on http://localhost:${process.env.APP_PORT}`)
}) })
await mongooseDB.init()
process.on('exit', () => { process.on('exit', () => {
mongooseDB.close() mongoose.disconnect()
}) })
} catch(err: unknown){ } catch(err: unknown){
console.log(err); console.log(err);
} }
}
} }
const app = new App(); run()
\ No newline at end of file
app.init();
\ 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