-
Notifications
You must be signed in to change notification settings - Fork 0
/
setupDatabase.js
96 lines (88 loc) · 3.17 KB
/
setupDatabase.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const { Client } = require('pg');
const { DB } = require('./config');
(async () => {
const usersTableStmt = `
CREATE TABLE IF NOT EXISTS users (
id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY NOT NULL,
email VARCHAR(50) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
firstName VARCHAR(50),
lastName VARCHAR(50),
google JSON,
facebook JSON
);
`;
const productsTableStmt = `
CREATE TABLE IF NOT EXISTS products (
id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY NOT NULL,
name VARCHAR(50) NOT NULL,
price BIGINT NOT NULL,
description VARCHAR(50) NOT NULL
);
`;
const ordersTableStmt = `
CREATE TABLE IF NOT EXISTS orders (
id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY NOT NULL,
total INT NOT NULL,
status VARCHAR(50) NOT NULL,
userId INT NOT NULL,
created DATE NOT NULL,
modified DATE NOT NULL,
FOREIGN KEY (userId) REFERENCES users(id)
);
`;
const orderItemsTableStmt = `
CREATE TABLE IF NOT EXISTS orderItems (
id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY NOT NULL,
created DATE NOT NULL,
orderId INT NOT NULL,
qty INT NOT NULL,
price INT NOT NULL,
productId INT NOT NULL,
name VARCHAR(50) NOT NULL,
description VARCHAR(200) NOT NULL,
FOREIGN KEY (orderId) REFERENCES orders(id)
);
`;
const cartsTableStmt = `
CREATE TABLE IF NOT EXISTS carts (
id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY NOT NULL,
userId INT NOT NULL,
modified DATE NOT NULL,
created DATE NOT NULL,
FOREIGN KEY (userId) REFERENCES users(id)
);
`;
const cartItemsTableStmt = `
CREATE TABLE IF NOT EXISTS cartItems (
id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY NOT NULL,
cartId INT NOT NULL,
productId INT NOT NULL,
qty INT NOT NULL,
FOREIGN KEY (cartId) REFERENCES carts(id),
FOREIGN KEY (productId) REFERENCES products(id)
);
`;
const client = new Client({
user: DB.PGUSER,
host: DB.PGHOST,
database: DB.PGDATABASE,
password: DB.PGPASSWORD,
port: DB.PGPORT,
});
try {
await client.connect();
// Create tables
await client.query(usersTableStmt);
await client.query(productsTableStmt);
await client.query(ordersTableStmt);
await client.query(orderItemsTableStmt);
await client.query(cartsTableStmt);
await client.query(cartItemsTableStmt);
console.log('Connected to database');
} catch (error) {
console.error('Error connecting to database', error);
} finally {
await client.end();
}
})();