Update README.md
[KisSync.git] / src / db / aliases.js
blob2e3ddc64e11473997dfb9fd23dbdf02dbd21fc2e
1 import net from 'net';
3 const LOGGER = require('@calzoneman/jsli')('AliasesDB');
5 class AliasesDB {
6 constructor(db) {
7 this.db = db;
10 async addAlias(ip, name) {
11 return this.db.runTransaction(async tx => {
12 try {
13 await tx.table('aliases')
14 .where({ ip, name })
15 .del();
16 await tx.table('aliases')
17 .insert({ ip, name, time: Date.now() });
18 } catch (error) {
19 LOGGER.error('Failed to save alias: %s (ip=%s, name=%s)',
20 error.message, ip, name);
22 });
25 async getAliasesByIP(ip) {
26 return this.db.runTransaction(async tx => {
27 const query = tx.table('aliases');
28 if (net.isIP(ip)) {
29 query.where({ ip: ip });
30 } else {
31 const delimiter = /^[0-9]+\./.test(ip) ? '.' : ':';
32 query.where('ip', 'LIKE', ip + delimiter + '%');
35 const rows = await query.select()
36 .distinct('name')
37 .orderBy('time', 'desc')
38 .limit(5);
39 return rows.map(row => row.name);
40 });
43 async getIPsByName(name) {
44 return this.db.runTransaction(async tx => {
45 const rows = await tx.table('aliases')
46 .select('ip')
47 .where({ name });
48 return rows.map(row => row.ip);
49 });
53 export { AliasesDB };