-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
133 lines (118 loc) · 5.23 KB
/
server.js
File metadata and controls
133 lines (118 loc) · 5.23 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
const { app, pool, ensureAuthenticated } = require('./app');
const port = 3000;
// Подключение маршрутов
const housesRouter = require('./routes/houses')(pool, ensureAuthenticated);
app.use('/api/houses', housesRouter);
// Функция для инициализации таблиц
const initDb = async () => {
try {
const client = await pool.connect();
console.log("Попытка инициализации таблиц...");
// 1. ТАБЛИЦА USERS
await client.query(`
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
google_id VARCHAR(255) UNIQUE NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
name VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
`);
// 2. ТАБЛИЦА HOUSES
await client.query(`
CREATE TABLE IF NOT EXISTS houses (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
zip_code TEXT,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL
);
`);
// 3. ТАБЛИЦА ROOMS
await client.query(`
CREATE TABLE IF NOT EXISTS rooms (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
house_id INTEGER REFERENCES houses(id) ON DELETE CASCADE,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL
);
`);
// 4. ТАБЛИЦА ITEMS
await client.query(`
CREATE TABLE IF NOT EXISTS items (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
type TEXT NOT NULL,
room_id INTEGER REFERENCES rooms(id) ON DELETE CASCADE,
parent_item_id INTEGER REFERENCES items(id) ON DELETE CASCADE,
is_on_floor BOOLEAN DEFAULT FALSE,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL
);
`);
// 5. ТАБЛИЦА GHOST_LOCATIONS (уже есть)
await client.query(`
CREATE TABLE IF NOT EXISTS ghost_locations (
id SERIAL PRIMARY KEY,
item_id INTEGER REFERENCES items(id) ON DELETE CASCADE NOT NULL,
location_name VARCHAR(255) NOT NULL,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL,
UNIQUE (item_id, location_name)
);
`);
// ======= НОВОЕ: memberships / invites / notifications / owner_id =======
await client.query(`
CREATE TABLE IF NOT EXISTS house_memberships (
id SERIAL PRIMARY KEY,
house_id INTEGER NOT NULL REFERENCES houses(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
role TEXT NOT NULL DEFAULT 'viewer',
created_at timestamptz DEFAULT now(),
UNIQUE (house_id, user_id)
);
`);
await client.query(`
CREATE TABLE IF NOT EXISTS house_invites (
id SERIAL PRIMARY KEY,
house_id INTEGER NOT NULL REFERENCES houses(id) ON DELETE CASCADE,
token TEXT NOT NULL UNIQUE,
role TEXT NOT NULL DEFAULT 'viewer',
created_by INTEGER REFERENCES users(id),
expires_at timestamptz,
used BOOLEAN DEFAULT false,
created_at timestamptz DEFAULT now()
);
`);
await client.query(`
CREATE TABLE IF NOT EXISTS notifications (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
payload JSONB,
message TEXT,
seen BOOLEAN DEFAULT false,
created_at timestamptz DEFAULT now()
);
`);
// owner_id для items (если ещё нет)
await client.query(`
ALTER TABLE items
ADD COLUMN IF NOT EXISTS owner_id INTEGER REFERENCES users(id);
`);
// дополнительные индексы (при необходимости)
await client.query(`CREATE INDEX IF NOT EXISTS idx_house_invites_token ON house_invites(token);`);
await client.query(`CREATE INDEX IF NOT EXISTS idx_house_memberships_house_id ON house_memberships(house_id);`);
await client.query(`CREATE INDEX IF NOT EXISTS idx_notifications_user_id ON notifications(user_id);`);
// ======= конец нового блока =======
client.release();
console.log("Таблицы успешно инициализированы или уже существуют.");
} catch (err) {
console.error('Ошибка инициализации базы данных:', err.stack);
// Не вызываем throw, чтобы сервер мог запуститься, но это плохая практика
}
};
const startServer = async () => {
await initDb();
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
};
startServer();