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.
89 lines
2.1 KiB
TypeScript
89 lines
2.1 KiB
TypeScript
import client from '../database'
|
|
|
|
export type Order = {
|
|
status: string
|
|
userId: number
|
|
}
|
|
|
|
export type OrderProduct = {
|
|
quantity: number
|
|
orderId: number
|
|
productId: 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(userId: string): Promise<Order> {
|
|
try {
|
|
|
|
const conn = await client.connect()
|
|
const sql = 'SELECT * FROM orders WHERE user_id=($1)'
|
|
|
|
const result = await conn.query(sql, [userId])
|
|
const order = result.rows[0]
|
|
|
|
conn.release()
|
|
|
|
return order
|
|
|
|
} catch (err) {
|
|
throw new Error(`Could not find order ${userId}. 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.userId])
|
|
const order = result.rows[0]
|
|
|
|
conn.release()
|
|
|
|
return order
|
|
|
|
} catch (err) {
|
|
throw new Error(`Could not add a new order ${o.userId}. Error: ${err}`)
|
|
}
|
|
}
|
|
|
|
async addProduct(o: OrderProduct): Promise<Order> {
|
|
try {
|
|
|
|
const conn = await client.connect()
|
|
const sql = 'INSERT INTO order_products (quantity, order_id, product_id) VALUES ($1, $2) RETURNING *'
|
|
|
|
const result = await conn.query(sql, [o.quantity, o.orderId, o.productId])
|
|
const order = result.rows[0]
|
|
|
|
conn.release()
|
|
|
|
return order
|
|
|
|
} catch (err) {
|
|
throw new Error(`Could not add a new orderProducts ${o.orderId}. Error: ${err}`)
|
|
}
|
|
}
|
|
|
|
|
|
} |