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.

91 lines
2.4 KiB
TypeScript

import { Client, Connection } from 'pg';
import client from '../database';
export type Product = {
id?: number;
name: string;
price: number;
}
export class ProductStore {
async index(): Promise<Product[]> {
try {
// @ts-ignore
const conn = await client.connect()
const sql = 'SELECT * FROM products;'
const result = await conn.query(sql)
conn.release()
return result.rows
} catch (err) {
throw new Error(`Cannot get products ${err}`)
}
}
async show(id: string): Promise<Product> {
try {
const sql = 'SELECT * FROM products where id=($1);'
// @ts-ignore
const conn = await client.connect()
const result = await conn.query(sql, [id])
conn.release()
return result.rows[0]
} catch (err) {
throw new Error(`Could not find product ${id}. Error: ${err}`)
}
}
async create(p: Product): Promise<Product> {
try {
const sql = 'INSERT INTO products (name, price) VALUES ($1, $2) RETURNING *;'
// @ts-ignore
const conn = await client.connect()
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 new product ${p.name}. Error: ${err}`)
}
}
async update(p: Product): Promise<Product> {
try {
const conn = await client.connect();
const result = await conn.query(
'UPDATE products SET name=$1, price=$2 WHERE id=$3 returning *;',
[p.name, p.price, p.id]
);
conn.release()
return result.rows[0]
} catch (err) {
throw new Error(`could not update product ${p.id}. Error: ${err}`)
}
}
async delete(id: number): Promise<Product> {
try {
const sql = 'DELETE FROM products WHERE id=(1$)'
// @ts-ignore
const conn = await client.connect()
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}`)
}
}
}