postgres connection and api, alpha

Vic
Vic 2 years ago
parent 351f6ddf4d
commit 7fa01964cd

@ -1 +0,0 @@
* @udacity/active-public-content

@ -0,0 +1,16 @@
{
"dev": {
"driver": "pg",
"host": "127.0.0.1",
"database": "shelf_dev",
"user": "postgres",
"password": "fredy123"
},
"test": {
"driver": "pg",
"host": "127.0.0.1",
"database": "shelf_test",
"user": "postgres_test",
"password": "fredy123"
}
}

@ -0,0 +1,7 @@
CREATE TABLE books (
id SERIAL PRIMARY KEY,
title VARCHAR(150),
author VARCHAR(255),
price integer not null,
summary text
);

@ -0,0 +1,24 @@
import { Pool } from 'pg';
import dotenv from 'dotenv';
dotenv.config();
const {
ENV,
POSTGRES_HOST,
POSTGRES_DB,
POSTGRES_USER,
POSTGRES_PASSWORD
} = process.env;
let client = new Pool();
if (ENV === 'dev') {
client = new Pool({
host: POSTGRES_HOST,
database: POSTGRES_DB,
user: POSTGRES_USER,
password: POSTGRES_PASSWORD
});
}
export default client

@ -0,0 +1,83 @@
import { Client } from 'pg';
import client from '../database';
//import { Books } from '../types';
export type Book = {
id: number;
title: string;
author: string;
price: number;
summary: string;
}
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, price, summary) VALUES ($1, $2, $3, $4) RETURNING *'
// @ts-ignore
const conn = await client.connect()
const result = await conn.query(sql, [b.title, b.author, b.price, b.summary])
const book = result.rows[0]
conn.release()
return book
} catch (err) {
throw new Error(`Could not add new book ${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}`)
}
}
}

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save