Skip to content

Commit bb642f7

Browse files
committed
Optimize fetchInstanceAP queries
1 parent f6741bf commit bb642f7

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

worker.js

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,19 +80,24 @@ async function fetchInstanceAP(options) {
8080
await instance.save();
8181

8282
try {
83-
let peers = await request({
83+
let peers = (await request({
8484
url: `https://${instance.name}/api/v1/instance/peers`,
8585
json: true
86-
});
86+
})).filter(p => isValidDomain(p, {allowUnicode: true, subdomain: true}))
87+
.map(p => p.toLowerCase());
88+
89+
let existing = await pg.query(pgFormat('SELECT lower(name) AS name FROM instances WHERE lower(name) IN (%L)', peers));
90+
let missing = peers.filter(p => !existing.rows.some(r => r.name === p));
8791

88-
let values = peers
89-
.filter(p => isValidDomain(p, {allowUnicode: true, subdomain: true}))
92+
let values = missing
9093
.map(p => [
9194
flake.gen(),
92-
p.toLowerCase()
95+
p
9396
]);
9497

95-
await pg.query(pgFormat('INSERT INTO instances(id, name) VALUES %L ON CONFLICT DO NOTHING RETURNING id,name', values));
98+
if(values.length !== 0) {
99+
await pg.query(pgFormat('INSERT INTO instances(id, name) VALUES %L', values));
100+
}
96101
} catch(e) {}
97102

98103
try {

0 commit comments

Comments
 (0)