Skip to content

Commit 6a0e0b3

Browse files
feat: method for insertMany itens on postgres
1 parent b853453 commit 6a0e0b3

File tree

4 files changed

+28
-10
lines changed

4 files changed

+28
-10
lines changed

package-lock.json

+9
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
"draftlog": "^1.0.13",
2525
"mongodb": "^6.5.0",
2626
"pg": "^8.11.5",
27+
"pg-format": "^1.0.4",
2728
"sqlite3": "^5.1.7"
2829
}
29-
}
30+
}

src/background-task.js

+7-9
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,11 @@ const db = await getPostgresConnection()
55

66
process.on('message', (items) => {
77
// console.log(` ${process.pid} received ${items.length} items`,);
8-
for (const item of items) {
9-
db.students.insert(item)
10-
.then(() => {
11-
process.send('item-done');
12-
})
13-
.catch((error) => {
14-
console.error(error);
15-
});
16-
}
8+
db.students.insertMany(items)
9+
.then(() => {
10+
process.send(items.length);
11+
})
12+
.catch((error) => {
13+
console.error(error);
14+
});
1715
});

src/db.js

+10
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { MongoClient } from 'mongodb';
22
import pg from 'pg';
3+
import format from 'pg-format';
34
const { Client } = pg;
45
// Connection URL for MongoDB
56

@@ -47,6 +48,15 @@ async function getPostgresConnection() {
4748

4849
await client.query(query, values);
4950

51+
},
52+
async insertMany(persons) {
53+
const query = format(
54+
'INSERT INTO students (name, email, age, registered_at) VALUES %L',
55+
persons.map((person) => [person.name, person.email, person.age, person.registered_at])
56+
);
57+
58+
await client.query(query);
59+
5060
},
5161
async list(limit = 100) {
5262
const query = 'SELECT * FROM students LIMIT $1';

0 commit comments

Comments
 (0)