You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.4 KiB
TypeScript

import client from '../database';
export type Product = {
id?: number;
name: string;
price: number;
}
export class ProductStore {
async index(): Promise<Product[]> {
try {
const conn = await client.connect()
const sql = 'SELECT * FROM products'
const result = await conn.query(sql)
const products = result.rows
conn.release()
return products
} catch (err) {
throw new Error(`Cannot get any products ${err}`)
}
}
async read(id: number): Promise<Product> {
try {
const conn = await client.connect()
const sql = 'SELECT * FROM products WHERE id=($1)'
const result = await conn.query(sql, [id])
const product = result.rows[0]
conn.release()
return product
} catch (err) {
throw new Error(`Could not find product ${id}. Error: ${err}`)
}
}
async create(p: Product): Promise<Product> {
try {
const conn = await client.connect()
const sql = 'INSERT INTO products (name, price) VALUES ($1, $2) RETURNING *'
const result = await conn.query(sql, [p.name, p.price])
const product = result.rows[0]
conn.release()
return product
} catch (err) {
throw new Error(`Could not add a new product ${p.name}. Error: ${err}`)
}
}
async update(p: Product): Promise<Product> {
try {
const conn = await client.connect();
const sql = 'UPDATE products SET name=$1, price=$2 WHERE id=$3 RETURNING *'
const result = await conn.query(sql, [p.name, p.price, p.id])
const product = result.rows[0]
conn.release()
return product
} catch (err) {
throw new Error(`Could not update product ${p.id}. Error: ${err}`)
}
}
async delete(id: number): Promise<Product> {
try {
const conn = await client.connect()
const sql = 'DELETE FROM products WHERE id=($1)'
const result = await conn.query(sql, [id])
const product = result.rows[0]
conn.release()
return product
} catch (err) {
throw new Error(`Could not delete product ${id}. Error: ${err}`)
}
}
}