Commit 8c49b3f3 authored by Pavel Mishakov's avatar Pavel Mishakov

lesson 86 done

parent 30c55e7f
This diff is collapsed.
......@@ -13,6 +13,7 @@
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"mongodb": "^5.1.0",
"multer": "^1.4.5-lts.1",
"nanoid": "^4.0.1",
"pg": "^8.9.0",
......@@ -25,6 +26,7 @@
"@types/cors": "^2.8.13",
"@types/dotenv": "^8.2.0",
"@types/express": "^4.17.17",
"@types/mongodb": "^4.0.7",
"@types/multer": "^1.4.7",
"@types/nanoid": "^3.0.0",
"@types/uuidv4": "^5.0.0",
......
......@@ -5,6 +5,7 @@ import multer from 'multer'
// import {nanoid} from 'nanoid'
// const {nanoid} = require('nanoid')
import { config } from '../index.config'
import { productServiceMongo } from '../services/productsMongo'
// import path from 'path'
const storage = multer.diskStorage({
......@@ -36,6 +37,9 @@ export class ProductsController {
case 'postgres':
this.service = productServicePg
break
case 'mongoDBCLient':
this.service = productServiceMongo
break
default:
this.service = productServicePg
}
......
......@@ -5,6 +5,8 @@ import { db } from './repository/fileDB'
import cors from 'cors'
import dotenv from 'dotenv'
import { postgresDB } from './repository/postgresDB'
import { mongoDBClient } from './repository/mongoDBClient'
import IDataBase from './interfaces/IDataBase'
dotenv.config()
......@@ -19,22 +21,30 @@ class App {
public init = async (): Promise<void> => {
try {
this.app.use('/health-check', new HealthCheckController().getRouter())
this.app.use('/products', new ProductsController().getRouter())
this.app.listen(process.env.APP_PORT, () => {
console.log(`Server is running on port ${process.env.APP_PORT}`)
})
let currentDb: IDataBase
switch(process.env.DB) {
case 'file':
db.init()
currentDb = db
break
case 'postgres':
await postgresDB.init()
currentDb = postgresDB
break
case 'mongoDBCLient':
currentDb = mongoDBClient
break
default:
await postgresDB.init()
currentDb = postgresDB
}
await currentDb.init()
process.on('exit', () => {
currentDb.close()
})
this.app.use('/health-check', new HealthCheckController().getRouter())
this.app.use('/products', new ProductsController().getRouter())
this.app.listen(process.env.APP_PORT, () => {
console.log(`Server is running on port ${process.env.APP_PORT}`)
})
} catch(err) {
console.log(err)
}
......
export default interface IDataBase {
init: () => Promise<void>
close: () => Promise<void> | void
}
\ No newline at end of file
......@@ -8,5 +8,5 @@ export default interface IProduct {
brand_id: string
description: string
suppliers?: ISupplier[]
image: string
image?: File | undefined | string
}
\ No newline at end of file
......@@ -4,5 +4,5 @@ export default interface IProductDto {
description: string
category_id: string
brand_id: string
image?: File
image?: File | undefined | string
}
\ No newline at end of file
......@@ -2,15 +2,16 @@ import IProduct from "../interfaces/IProduct";
import fs from 'node:fs/promises'
import { uuid } from 'uuidv4';
import IProductDto from "../interfaces/IProductDto";
import IDataBase from "../interfaces/IDataBase";
class FileDB {
class FileDB implements IDataBase {
data: IProduct[]
filename: string
constructor() {
this.data = []
this.filename = './db/db.json'
}
init = async () => {
public init = async () => {
try {
const fileContents = await fs.readFile(this.filename, {encoding: 'utf-8'});
this.data = JSON.parse(fileContents);
......@@ -26,21 +27,27 @@ class FileDB {
}
}
getItems = () => {
public close = (): void => {
return undefined
}
public getItems = () => {
return this.data;
}
getItemById = (id: string) => {
public getItemById = (id: string) => {
return this.data.find(p => p.id === id);
}
addItem = (item: IProductDto): IProduct => {
public addItem = (item: IProductDto): IProduct => {
const id: string = uuid()
const product: IProduct = {...item, id}
this.data.push(product);
this.save();
return product
}
save = async () => {
try {
......
import { MongoClient, Db } from 'mongodb'
import dotenv from 'dotenv'
import IDataBase from '../interfaces/IDataBase'
dotenv.config()
export class MongoDBClient implements IDataBase {
private client: MongoClient | null = null
private db: Db | null = null
public getDb = (): Db | null => {
return this.db
}
public close = async(): Promise<void> => {
if (!this.client) return
await this.client.close()
}
public init = async (): Promise<void> => {
this.client = await MongoClient.connect(process.env.MONGO_CLIENT_URL || '')
this.db = this.client.db('myStore')
console.log('MongoDBClient is connected')
}
}
export const mongoDBClient = new MongoDBClient()
\ No newline at end of file
......@@ -4,8 +4,9 @@ import dotenv from 'dotenv'
import { Sequelize } from 'sequelize-typescript'
dotenv.config()
import path from 'path'
import IDataBase from '../interfaces/IDataBase'
export class PostgresDB {
export class PostgresDB implements IDataBase {
private sequelize: Sequelize
constructor() {
this.sequelize = new Sequelize({
......
import { EStatuses } from "../enums/EStatuses"
import IProductDto from "../interfaces/IProductDto"
import IResponse from "../interfaces/IResponse"
import { ObjectId } from 'mongodb'
import { mongoDBClient } from '../repository/mongoDBClient'
export class ProductServiceMongo {
public getProducts = async (): Promise<IResponse> => {
try {
const data = await mongoDBClient.getDb()?.collection('products').find().toArray()
const response: IResponse = {
status: EStatuses.OK,
result: data as any,
message: 'Products found'
}
return response
} catch (err: unknown) {
const error = err as Error
const response: IResponse = {
status: EStatuses.NOT_OK,
result: undefined,
message: error.message
}
return response
}
}
public getProductById = async (id: string): Promise<IResponse> => {
try {
const data = await mongoDBClient.getDb()?.collection('products').findOne({_id: new ObjectId(id)})
const response: IResponse = {
status: EStatuses.OK,
result: data as any,
message: ''
}
return response
} catch (err: unknown) {
const error = err as Error
const response: IResponse = {
status: EStatuses.NOT_OK,
result: undefined,
message: error.message
}
return response
}
}
public addProduct = async (product: IProductDto): Promise<IResponse> => {
try {
const data = await mongoDBClient.getDb()?.collection('products').insertOne({...product})
console.log('PRODUCT DATA:::: ', data)
const response: IResponse = {
status: EStatuses.OK,
result: data as any,
message: ''
}
return response
} catch (err: unknown) {
const error = err as Error
const response: IResponse = {
status: EStatuses.NOT_OK,
result: undefined,
message: error.message
}
return response
}
}
}
export const productServiceMongo = new ProductServiceMongo()
\ 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