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

lesson 86

parent b93f828b
This diff is collapsed.
......@@ -17,9 +17,11 @@
"cors": "^2.8.5",
"express": "^4.18.2",
"multer": "^1.4.5-lts.1",
"mysql2": "^3.9.4",
"reflect-metadata": "^0.2.1",
"ts-node": "^10.9.1",
"tslib": "^2.6.0",
"typeorm": "^0.3.20",
"typescript": "^5.1.6"
},
"devDependencies": {
......
......@@ -2,6 +2,7 @@ import express from 'express';
import { Application, RequestHandler } from 'express';
import { AppInit } from './interfaces/AppInit.interface';
import { IRoute } from './interfaces/IRoute.interface';
import { appDataSource } from '@/config/dataSource';
class App {
public app: Application;
......@@ -28,9 +29,13 @@ class App {
this.app.use(express.json());
this.app.use(express.static('public'));
}
public listen() {
public async listen() {
await appDataSource.initialize();
this.app.listen(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 {
this.service = new ProductService();
}
getProducts: RequestHandler = (req, res): void => {
const products = this.service.getProducts();
getProducts: RequestHandler = async (req, res): Promise<void> => {
const products = await this.service.getProducts();
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);
} 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);
if (req.file) productDto.image = req.file.filename;
const product = this.service.createProduct(productDto);
const product = await this.service.createProduct(productDto);
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 {
id: string;
id: number;
title: string;
price: number;
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 { ProductDto } from '@/dto/ProductDto';
import * as fs from 'fs';
import path from 'path';
import { randomUUID } from 'crypto';
const filePath = path.join(__dirname, '../data/products.json');
import { ProductRepository } from '@/repositories/product.repository';
export class ProductService {
private products: IProduct[] = [];
private repository: ProductRepository;
constructor() {
this.init();
}
private init() {
try {
const fileContents = fs.readFileSync(filePath);
this.products = JSON.parse(fileContents.toString());
} catch (e) {
this.products = [];
}
this.repository = new ProductRepository();
}
private save() {
fs.writeFileSync(filePath, JSON.stringify(this.products, null, 2));
public async getProducts(): Promise<IProduct[]> {
return await this.repository.getProducts();
}
public getProducts(): IProduct[] {
return this.products;
}
public getProduct(id: string): IProduct {
const singleProduct = this.products.find((product) => product.id === id);
if (singleProduct) return singleProduct;
public async getProduct(id: number): Promise<IProduct> {
const product = await this.repository.getProduct(id);
if (product) return product;
else throw new Error('Invalid id');
}
public createProduct(productDto: ProductDto): IProduct {
const product = {
id: randomUUID(),
...productDto,
};
this.products.push(product);
this.save();
return product;
public async createProduct(productDto: ProductDto): Promise<IProduct> {
return await this.repository.createProduct(productDto);
}
}
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