import { Injectable } from '@nestjs/common';
import { DataSource } from 'typeorm';
@Injectable()
export class RawProductsService {
constructor(private readonly dataSource: DataSource) {}
// 1. Thêm mới dữ liệu (INSERT)
async insertProduct(name: string, price: number, description: string) {
const sql = `
INSERT INTO products (name, price, description)
VALUES ($1, $2, $3)
RETURNING id, name, price;
`;
// Thực thi lệnh và nhận lại dòng dữ liệu vừa thêm nhờ từ khóa RETURNING
const result = await this.dataSource.query(sql, [name, price, description]);
return result[0];
}
// 2. Cập nhật dữ liệu (UPDATE)
async updateProductPrice(id: number, newPrice: number) {
const sql = `
UPDATE products
SET price = $1
WHERE id = $2;
`;
await this.dataSource.query(sql, [newPrice, id]);
return { success: true, message: `Cập nhật thành công sản phẩm #${id}` };
}
// 3. Xóa dữ liệu (DELETE)
async deleteProduct(id: number) {
const sql = `
DELETE FROM products
WHERE id = $1;
`;
await this.dataSource.query(sql, [id]);
return { success: true, message: `Xóa thành công sản phẩm #${id}` };
}
}