Commit 1f83bb7e authored by Цой Данил's avatar Цой Данил 💬

Added repository + healthCheckController. Connect to main index file. Planning to test it

parent ccee784a
import express, { Router, 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
import jwt from 'jsonwebtoken'
import { Types } from 'mongoose'
export const generateJWT = (payload: {[key: string]: number | string | boolean | Types.ObjectId}) => {
return jwt.sign(payload, process.env.SECRET_KEY || 'key', {expiresIn: '24h'})
}
import express, { Express } from "express";
import dotenv from 'dotenv';
import cors from 'cors';
import { healthCheckController } from "./controllers/healthCheckController";
dotenv.config()
class App {
private app: Express
constructor(){
this.app = express()
this.app.use(express.json())
this.app.use(express.static('public'))
this.app.use(cors())
}
public init = async(): Promise<void> => {
try{
this.app.use('/health-check', healthCheckController.getRouter())
this.app.listen(process.env.APP_PORT, () => {
console.log(`Server is running on http://localhost:${process.env.APP_PORT}`);
})
} catch(err: unknown){
console.log(err);
}
}
}
\ No newline at end of file
......@@ -2,7 +2,6 @@ import { NextFunction, Request, Response } from "express";
import { EStatuses } from "../enum/EStatuses";
import IResponse from "../interfaces/IResponse";
import jwt from 'jsonwebtoken'
import IRequestWithTokenData from "../interfaces/IModifiedRequest";
import IModifiedRequest from "../interfaces/IModifiedRequest";
......
import mongoose, { Schema } from "mongoose";
import IPhoto from "../interfaces/IPhoto";
const PhotoSchema: Schema = new Schema<IPhoto>({
title:{
type: String,
trim: true,
minlength: 1,
required: [true, 'Title should exist']
},
photo:{
type: String,
require: true,
trim: true,
minlength: 1,
required: [true, 'Photo should exist']
},
user:{
type: Schema.Types.ObjectId,
ref: 'User',
required: [true, 'User data should exist']
}
}, {versionKey: false})
export const Photo = mongoose.model<IPhoto>('Photo', PhotoSchema)
\ No newline at end of file
import mongoose, { Schema } from "mongoose";
import bcrypt from "bcrypt";
import IUser from "../interfaces/IUser";
const UserSchema: Schema = new Schema<IUser>({
username: {
type: String,
unique: true,
trim: true,
minlength: 1,
required: [true, 'Username should exist']
},
password: {
type: String,
trim: true,
minlength: 1,
required: [true, 'Password should exist']
}
}, {versionKey: false})
UserSchema.pre('save', async function (next){
if (!this.isModified('password')) return next()
const salt = await bcrypt.genSalt()
const hash = await bcrypt.hash(this.password, salt)
this.password = hash
next()
})
UserSchema.set('toJSON', {transform(doc, ret, options) {
delete ret.password
return ret
}})
UserSchema.methods.checkPassword = async function(password: string) {
return await bcrypt.compare(password, this.password);
}
export const User = mongoose.model<IUser>('User', UserSchema)
import dotenv from 'dotenv';
import mongoose, { Mongoose } from 'mongoose';
import IUserCreateDto from '../interfaces/IUserCreateDto';
import IResponse from '../interfaces/IResponse';
import IUserGetDto from '../interfaces/IUserGetDto';
import { User } from '../models/User';
import { EStatuses } from '../enum/EStatuses';
import { generateJWT } from '../helpers/generateJWT';
import IPhotoDto from '../interfaces/IPhotoDto';
import IPhoto from '../interfaces/IPhoto';
import { Photo } from '../models/Photo';
dotenv.config()
export class MongooseDB {
private client: Mongoose | null = null
public close = async() => {
if (!this.client) return
await this.client.disconnect();
}
public init = async (): Promise<void> => {
try {
this.client = await mongoose.connect(process.env.MONGO_CLIENT_URL || '')
console.log('Server connected to MongoDB');
} catch (err) {
const error = err as Error;
console.error('Connected error MongooseDB:', error);
}
}
public createUser = async (userDto: IUserCreateDto): Promise<IResponse<IUserGetDto | null>> => {
try{
const user = new User(userDto)
const data: IUserGetDto = {
_id: user._id,
username: user.username,
token: generateJWT({_id: user._id, username: user.username})
}
const response: IResponse<IUserGetDto> = {
status: EStatuses.SUCCESS,
result: data,
message: 'User created'
}
await user.save()
return response
} catch(err: unknown){
const error = err as Error
const response: IResponse<null> = {
status: EStatuses.FAILURE,
result: null,
message: error.message
}
return response
}
}
public loginUser = async(userDto: IUserCreateDto): Promise<IResponse<IUserGetDto | null>> => {
try{
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')
const data = {
_id: user._id,
username: user.username,
token: generateJWT({_id: user._id, username: user.username})
}
await user.save()
const response: IResponse<IUserGetDto> = {
status: EStatuses.SUCCESS,
result: data,
message: 'Access granted'
}
return response
} catch(err: unknown){
const error = err as Error
const response: IResponse<null> = {
status: EStatuses.FAILURE,
result: null,
message: error.message
}
return response
}
}
public getAllPhotos = async (): Promise<IResponse<IPhoto[] | null>> => {
try{
const data = await Photo.find().populate('user')
const response: IResponse<IPhoto[]> = {
status: EStatuses.SUCCESS,
result: data,
message: 'Photos found successfully'
}
return response
} catch(err: unknown){
const error = err as Error
const response: IResponse<null> = {
status: EStatuses.FAILURE,
result: null,
message: error.message
}
return response
}
}
public addPhoto = async(photoDto: IPhotoDto): Promise<IResponse<IPhoto | null>> => {
try{
const user = await User.findOne({_id: photoDto.user})
if (!user) throw new Error ('User not found!')
const photo = new Photo(photoDto)
const data = await photo.save()
const responseData = await data.populate('user')
const response: IResponse<IPhoto> = {
status: EStatuses.SUCCESS,
result: responseData,
message: 'Photo added'
}
return response
} catch(err: unknown){
const error = err as Error
const response: IResponse<null> = {
status: EStatuses.FAILURE,
result: null,
message: error.message
}
return response
}
}
public deletePhotoById = async(id: string, user: string): Promise<IResponse<IPhoto | null>> => {
try{
const photo = await Photo.findOneAndDelete({_id: id, user: user})
if (!photo) throw new Error('No photo with stated id was found')
const response: IResponse<IPhoto> = {
status: EStatuses.SUCCESS,
result: photo,
message: 'Photo was deleted successfully'
}
return response
} catch(err: unknown){
const error = err as Error
const response: IResponse<null> = {
status: EStatuses.FAILURE,
result: null,
message: error.message
}
return response
}
}
public getPhotosByUserId = async(id: string): Promise<IResponse<IPhoto[] | null>> => {
try{
const data = await Photo.find({user: id}).populate('user')
const response: IResponse<IPhoto[]> = {
status: EStatuses.SUCCESS,
result: data,
message: 'Photos found successfully'
}
return response
} catch(err: unknown){
const error = err as Error
const response: IResponse<null> = {
status: EStatuses.FAILURE,
result: null,
message: error.message
}
return response
}
}
}
export const mongooseDB = new MongooseDB()
\ 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