-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathdb.js
More file actions
97 lines (78 loc) · 2.87 KB
/
db.js
File metadata and controls
97 lines (78 loc) · 2.87 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
import { MongoClient } from 'mongodb';
import pg from 'pg';
import format from 'pg-format';
const { Client } = pg;
// Connection URL for MongoDB
// Connection pool for PostgreSQL
async function getMongoConnection() {
const mongoUrl = 'mongodb://root:example@localhost:27017';
const client = new MongoClient(mongoUrl);
try {
await client.connect();
const dbName = 'school';
const db = client.db(dbName);
const collection = db.collection('students');
return {
students: collection,
client,
};
} catch (error) {
console.error('Error connecting to MongoDB:', error);
throw error;
}
}
async function getPostgresConnection() {
const client = new Client({
user: 'erickwendel',
host: 'localhost',
database: 'school',
password: 'mypassword',
port: 5432,
});
await client.connect();
return {
client,
students: {
async insert(person) {
const { name, email, age, registeredAt } = person;
const query = 'INSERT INTO students (name, email, age, registered_at) VALUES ($1, $2, $3, $4)';
const values = [name, email, age, registeredAt];
await client.query(query, values);
},
async insertMany(persons) {
const query = format(
'INSERT INTO students (name, email, age, registered_at) VALUES %L',
persons.map((person) => [person.name, person.email, person.age, person.registered_at])
);
await client.query(query);
},
async list(limit = 100) {
const query = 'SELECT * FROM students LIMIT $1';
const values = [limit];
const result = await client.query(query, values);
return result.rows;
},
async count() {
const query = 'SELECT COUNT(*) as total FROM students';
const result = await client.query(query);
return Number(result.rows[0].total);
},
async deleteAll() {
const query = 'DELETE FROM students';
await client.query(query);
},
async createTable() {
const createStudentsTableQuery = `
CREATE TABLE IF NOT EXISTS students (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
age INT NOT NULL,
registered_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)`;
await client.query(createStudentsTableQuery);
}
}
};
}
export { getMongoConnection, getPostgresConnection };