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.
93 lines
2.6 KiB
TypeScript
93 lines
2.6 KiB
TypeScript
import { Client, Connection } from 'pg';
|
|
import client from '../database';
|
|
|
|
export type Product = {
|
|
id?: string;
|
|
title: string;
|
|
author: string;
|
|
pages: number;
|
|
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 any product ${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 (title, author, pages, price) VALUES ($1, $2, $3, $4) RETURNING *;'
|
|
// @ts-ignore
|
|
const conn = await client.connect()
|
|
|
|
const result = await conn.query(sql, [p.title, p.author, p.pages, p.price])
|
|
const product = result.rows[0]
|
|
|
|
conn.release()
|
|
|
|
return product
|
|
} catch (err) {
|
|
throw new Error(`Could not add new product ${p.title}. Error: ${err}`)
|
|
}
|
|
|
|
}
|
|
|
|
async update(p: Product): Promise<Product> {
|
|
try {
|
|
const conn = await client.connect();
|
|
const result = await conn.query(
|
|
'UPDATE products SET title=$1, author=$2, pages=$3, price=$4 where id=$5 returning *;',
|
|
[p.title, p.author, p.pages, p.id]
|
|
);
|
|
conn.release()
|
|
return result.rows[0]
|
|
} catch (err) {
|
|
throw new Error(`could not update product ${p.id}. Error: ${err}`)
|
|
}
|
|
}
|
|
|
|
async delete(id: string): 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}`)
|
|
}
|
|
}
|
|
}
|