Commit 6628fe08 authored by Kulpybaev Ilyas's avatar Kulpybaev Ilyas

lesson 86

parent b93f828b
This diff is collapsed.
...@@ -17,9 +17,11 @@ ...@@ -17,9 +17,11 @@
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^4.18.2", "express": "^4.18.2",
"multer": "^1.4.5-lts.1", "multer": "^1.4.5-lts.1",
"mysql2": "^3.9.4",
"reflect-metadata": "^0.2.1", "reflect-metadata": "^0.2.1",
"ts-node": "^10.9.1", "ts-node": "^10.9.1",
"tslib": "^2.6.0", "tslib": "^2.6.0",
"typeorm": "^0.3.20",
"typescript": "^5.1.6" "typescript": "^5.1.6"
}, },
"devDependencies": { "devDependencies": {
......
...@@ -2,6 +2,7 @@ import express from 'express'; ...@@ -2,6 +2,7 @@ import express from 'express';
import { Application, RequestHandler } from 'express'; import { Application, RequestHandler } from 'express';
import { AppInit } from './interfaces/AppInit.interface'; import { AppInit } from './interfaces/AppInit.interface';
import { IRoute } from './interfaces/IRoute.interface'; import { IRoute } from './interfaces/IRoute.interface';
import { appDataSource } from '@/config/dataSource';
class App { class App {
public app: Application; public app: Application;
...@@ -28,9 +29,13 @@ class App { ...@@ -28,9 +29,13 @@ class App {
this.app.use(express.json()); this.app.use(express.json());
this.app.use(express.static('public')); this.app.use(express.static('public'));
} }
public listen() { public async listen() {
await appDataSource.initialize();
this.app.listen(this.port, () => { this.app.listen(this.port, () => {
console.log(`App listening on the http://localhost:${this.port}`); console.log(`App listening on the http://localhost:${this.port}`);
process.on('exit', () => {
appDataSource.destroy();
});
}); });
} }
} }
......
import { DataSource } from 'typeorm';
import { Product } from '@/entities/product.entity';
export const appDataSource = new DataSource({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'ilyas',
password: 'ilyas100890',
database: 'test',
synchronize: true,
logging: true,
entities: [Product],
});
...@@ -10,18 +10,24 @@ export class ProductController { ...@@ -10,18 +10,24 @@ export class ProductController {
this.service = new ProductService(); this.service = new ProductService();
} }
getProducts: RequestHandler = (req, res): void => { getProducts: RequestHandler = async (req, res): Promise<void> => {
const products = this.service.getProducts(); const products = await this.service.getProducts();
res.send(products); res.send(products);
}; };
getProduct: RequestHandler = (req, res): void => {
const product = this.service.getProduct(req.params.id); getProduct: RequestHandler = async (req, res): Promise<void> => {
try {
const product = await this.service.getProduct(Number(req.params.id));
res.send(product); res.send(product);
} catch (e) {
res.status(400).send({ message: (e as Error).message });
}
}; };
createProduct: RequestHandler = (req, res): void => {
createProduct: RequestHandler = async (req, res): Promise<void> => {
const productDto = plainToInstance(ProductDto, req.body); const productDto = plainToInstance(ProductDto, req.body);
if (req.file) productDto.image = req.file.filename; if (req.file) productDto.image = req.file.filename;
const product = this.service.createProduct(productDto); const product = await this.service.createProduct(productDto);
res.send(product); res.send(product);
}; };
} }
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity({ name: 'products' })
export class Product {
@PrimaryGeneratedColumn()
id!: number;
@Column()
title!: string;
@Column()
price!: number;
@Column()
image?: string;
@Column()
description!: string;
}
export interface IProduct { export interface IProduct {
id: string; id: number;
title: string; title: string;
price: number; price: number;
description?: string; description?: string;
......
import mysql, { Pool } from 'mysql2/promise';
let pool: Pool;
export const connect = async () => {
pool = mysql.createPool({
host: 'localhost',
user: 'ilyas',
password: 'ilyas100890',
database: 'test',
});
};
export const disconnect = async () => {
await pool.end();
};
export const getDb = () => pool;
import { IProduct } from '@/interfaces/IProduct.interface';
import { ProductDto } from '@/dto/ProductDto';
import { Repository } from 'typeorm';
import { appDataSource } from '@/config/dataSource';
import { Product } from '@/entities/product.entity';
export class ProductRepository extends Repository<Product> {
constructor() {
super(Product, appDataSource.createEntityManager());
}
async getProducts(): Promise<IProduct[]> {
return await this.find();
}
async getProduct(id: number): Promise<IProduct> {
const product = await this.findOne({
where: { id },
});
if (!product) {
throw new Error('Продукта с таким id не существует');
}
return product;
}
async createProduct(productDto: ProductDto): Promise<IProduct> {
const { title, description, price, image } = productDto;
const product = new Product();
product.image = image;
product.title = title;
product.price = price;
product.description = description;
await this.save(product);
return product;
}
}
import { IProduct } from '@/interfaces/IProduct.interface'; import { IProduct } from '@/interfaces/IProduct.interface';
import { ProductDto } from '@/dto/ProductDto'; import { ProductDto } from '@/dto/ProductDto';
import * as fs from 'fs'; import { ProductRepository } from '@/repositories/product.repository';
import path from 'path';
import { randomUUID } from 'crypto';
const filePath = path.join(__dirname, '../data/products.json');
export class ProductService { export class ProductService {
private products: IProduct[] = []; private repository: ProductRepository;
constructor() { constructor() {
this.init(); this.repository = new ProductRepository();
}
private init() {
try {
const fileContents = fs.readFileSync(filePath);
this.products = JSON.parse(fileContents.toString());
} catch (e) {
this.products = [];
}
} }
private save() { public async getProducts(): Promise<IProduct[]> {
fs.writeFileSync(filePath, JSON.stringify(this.products, null, 2)); return await this.repository.getProducts();
} }
public getProducts(): IProduct[] { public async getProduct(id: number): Promise<IProduct> {
return this.products; const product = await this.repository.getProduct(id);
} if (product) return product;
public getProduct(id: string): IProduct {
const singleProduct = this.products.find((product) => product.id === id);
if (singleProduct) return singleProduct;
else throw new Error('Invalid id'); else throw new Error('Invalid id');
} }
public createProduct(productDto: ProductDto): IProduct { public async createProduct(productDto: ProductDto): Promise<IProduct> {
const product = { return await this.repository.createProduct(productDto);
id: randomUUID(),
...productDto,
};
this.products.push(product);
this.save();
return product;
} }
} }
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