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.
80 lines
2.0 KiB
TypeScript
80 lines
2.0 KiB
TypeScript
import { Client } from 'pg';
|
|
import client from '../database';
|
|
//import { Book } from '../types';
|
|
|
|
export type Book = {
|
|
id?: string;
|
|
title: string;
|
|
author: string;
|
|
pages: number;
|
|
price: number;
|
|
}
|
|
|
|
export class BookStore {
|
|
async index(): Promise<Book[]> {
|
|
try {
|
|
// @ts-ignore
|
|
const conn = await client.connect()
|
|
const sql = 'SELECT * FROM books'
|
|
|
|
const result = await conn.query(sql)
|
|
conn.release()
|
|
return result.rows
|
|
} catch (err) {
|
|
throw new Error(`Cannot get any books ${err}`)
|
|
}
|
|
}
|
|
|
|
async show(id: string): Promise<Book> {
|
|
try {
|
|
const sql = 'SELECT * FROM books 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 book ${id}. Error: ${err}`)
|
|
}
|
|
|
|
}
|
|
|
|
async create(b: Book): Promise<Book> {
|
|
try {
|
|
const sql = 'INSERT INTO books (title, author, pages, price) VALUES ($1, $2, $3, $4) RETURNING *'
|
|
// @ts-ignore
|
|
const conn = await client.connect()
|
|
|
|
const result = await conn.query(sql, [b.title, b.author, b.pages, b.price])
|
|
const book = result.rows[0]
|
|
|
|
conn.release()
|
|
|
|
return book
|
|
} catch (err) {
|
|
throw new Error(`Could not add new book ${b.title}. Error: ${err}`)
|
|
}
|
|
|
|
}
|
|
|
|
async delete(id: string): Promise<Book> {
|
|
try {
|
|
const sql = 'DELETE FROM books WHERE id=(1$)'
|
|
// @ts-ignore
|
|
const conn = await client.connect()
|
|
|
|
const result = await conn.query(sql, [id])
|
|
const book = result.rows[0]
|
|
|
|
conn.release()
|
|
|
|
return book
|
|
|
|
} catch (err) {
|
|
throw new Error(`Could not delete book ${id}. Error: ${err}`)
|
|
}
|
|
}
|
|
}
|