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.

135 lines
3.5 KiB
TypeScript

import client from '../database'
export type Order = {
id?: number
status: string
user_id: number
}
export type OrderProduct = {
id?: number
quantity: number
order_id: number
product_id: number
}
export class OrderStore {
async index(): Promise<Order[]> {
try {
const conn = await client.connect()
const sql = 'SELECT * FROM orders'
const result = await conn.query(sql)
const orders = result.rows
conn.release()
return orders
} catch (err) {
throw new Error(`Cannot get any order ${err}`)
}
}
async read(user_id: number): Promise<Order> {
try {
const conn = await client.connect()
const sql = 'SELECT * FROM orders WHERE user_id=($1)'
const result = await conn.query(sql, [user_id])
const order = result.rows[0]
conn.release()
return order
} catch (err) {
throw new Error(`Could not find order ${user_id}. Error: ${err}`)
}
}
async create(o: Order): Promise<Order> {
try {
const conn = await client.connect()
const sql = 'INSERT INTO orders (status, user_id) VALUES ($1, $2) RETURNING *'
const result = await conn.query(sql, [o.status, o.user_id])
const order = result.rows[0]
conn.release()
return order
} catch (err) {
throw new Error(`Could not add a new order ${o.user_id}. Error: ${err}`)
}
}
async addProduct(o: OrderProduct): Promise<OrderProduct> {
try {
const ordersql = 'SELECT * FROM orders WHERE id=($1)'
const conn = await client.connect()
const result = await conn.query(ordersql, [o.order_id])
const order = result.rows[0]
if(order.status !== "active") {
throw new Error(`Could not add product ${o.product_id} to order ${o.order_id} because order status is ${order.status}`)
}
conn.release()
} catch (err) {
throw new Error(`${err}`)
}
try {
const sql = 'INSERT INTO order_products (quantity, order_id, product_id) VALUES ($1, $2, $3) RETURNING *'
const conn = await client.connect()
const result = await conn.query(sql, [o.quantity, o.order_id, o.product_id])
const order = result.rows[0]
conn.release()
return order
} catch (err) {
throw new Error(`Could not add product ${o.product_id} to order ${o.order_id}: Error: ${err}`)
}
}
async deleteProduct(id: number): Promise<Order> {
try {
const sql = 'DELETE FROM order_products WHERE order_id=($1)'
const conn = await client.connect()
const result = await conn.query(sql, [id])
conn.release()
} catch (err) {
throw new Error(`Could not delete order ${id}: Error: ${err}`)
}
try {
const ordersql = 'DELETE FROM orders WHERE id=($1)'
const conn = await client.connect()
const ordersResult = await conn.query(ordersql, [id])
const order = ordersResult.rows[0]
conn.release()
return order
} catch (err) {
throw new Error(`${err}`)
}
}
}