Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Contribute to GitLab
Sign in
Toggle navigation
H
Homework_95_Tsoy_Danil
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Цой Данил
Homework_95_Tsoy_Danil
Commits
41373fad
Commit
41373fad
authored
Apr 12, 2023
by
Цой Данил
💬
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Added routes for backend
parent
26a5a882
Hide whitespace changes
Inline
Side-by-side
Showing
7 changed files
with
248 additions
and
141 deletions
+248
-141
healthCheck.ts
backend/src/controllers/healthCheck.ts
+4
-19
messagesController.ts
backend/src/controllers/messagesController.ts
+57
-55
usersController.ts
backend/src/controllers/usersController.ts
+68
-35
index.ts
backend/src/index.ts
+24
-32
healthCheckRouter.ts
backend/src/routes/healthCheckRouter.ts
+8
-0
messagesRouter.ts
backend/src/routes/messagesRouter.ts
+76
-0
usersRoute.ts
backend/src/routes/usersRoute.ts
+11
-0
No files found.
backend/src/controllers/healthCheck.ts
View file @
41373fad
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
=
new
HealthCheckController
()
\ No newline at end of file
export
const
healthCheckController
=
async
(
req
:
Request
,
res
:
Response
)
=>
{
res
.
status
(
200
).
send
(
'Server is ok'
)
}
\ No newline at end of file
backend/src/controllers/messagesController.ts
View file @
41373fad
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
backend/src/controllers/usersController.ts
View file @
41373fad
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
)
}
public
getRouter
=
()
=>
{
return
this
.
router
}
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
)
}
public
loginUser
=
async
(
req
:
Request
,
res
:
Response
):
Promise
<
void
>
=>
{
const
response
:
IResponse
<
IUserGetDto
|
null
>
=
await
this
.
service
.
loginUser
(
req
.
body
)
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
})
}
const
response
:
IResponse
<
IUserGetDto
>
=
{
status
:
EStatuses
.
SUCCESS
,
result
:
responseData
,
message
:
'User added'
}
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
const
response
:
IResponse
<
IUserGetDto
|
null
>
=
{
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
:
re
q
.
verifiedData
as
IUserGetDto
,
message
:
'
Token is ok
'
result
:
re
sponseData
,
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
)
}
}
export
const
usersController
=
new
UsersController
()
\ No newline at end of file
export
const
checkToken
=
async
(
req
:
Request
,
res
:
Response
):
Promise
<
void
>
=>
{
const
modifiedReq
=
req
as
IModifiedRequest
const
response
:
IResponse
<
IUserGetDto
|
null
>
=
{
status
:
EStatuses
.
SUCCESS
,
result
:
modifiedReq
.
verifiedData
as
IUserGetDto
,
message
:
'Token is ok'
}
res
.
status
(
200
).
send
(
response
)
}
backend/src/index.ts
View file @
41373fad
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
>
=>
{
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
}
`
)
})
await
mongooseDB
.
init
()
process
.
on
(
'exit'
,
()
=>
{
mongooseDB
.
close
()
})
}
catch
(
err
:
unknown
){
console
.
log
(
err
);
}
const
run
=
async
():
Promise
<
void
>
=>
{
try
{
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
}
`
);
})
process
.
on
(
'exit'
,
()
=>
{
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
backend/src/routes/healthCheckRouter.ts
0 → 100644
View file @
41373fad
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
backend/src/routes/messagesRouter.ts
0 → 100644
View file @
41373fad
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
backend/src/routes/usersRoute.ts
0 → 100644
View file @
41373fad
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
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment