Add knex AliasesDB
This commit is contained in:
parent
76e0d1b7ec
commit
7ebf3c18ab
4 changed files with 254 additions and 1 deletions
59
src/db/aliases.js
Normal file
59
src/db/aliases.js
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
// @flow
|
||||
|
||||
import { Database } from '../database';
|
||||
import { LoggerFactory } from '@calzoneman/jsli';
|
||||
import net from 'net';
|
||||
|
||||
const LOGGER = LoggerFactory.getLogger('AliasesDB');
|
||||
|
||||
class AliasesDB {
|
||||
db: Database;
|
||||
|
||||
constructor(db: Database) {
|
||||
this.db = db;
|
||||
}
|
||||
|
||||
async addAlias(ip: string, name: string) {
|
||||
return this.db.runTransaction(async tx => {
|
||||
try {
|
||||
await tx.table('aliases')
|
||||
.where({ ip, name })
|
||||
.del();
|
||||
await tx.table('aliases')
|
||||
.insert({ ip, name, time: Date.now() });
|
||||
} catch (error) {
|
||||
LOGGER.error('Failed to save alias: %s (ip=%s, name=%s)',
|
||||
error.message, ip, name);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async getAliasesByIP(ip: string): Promise<Array<string>> {
|
||||
return this.db.runTransaction(async tx => {
|
||||
const query = tx.table('aliases');
|
||||
if (net.isIP(ip)) {
|
||||
query.where({ ip: ip })
|
||||
} else {
|
||||
const delimiter = /^[0-9]+\./.test(ip) ? '.' : ':';
|
||||
query.where('ip', 'LIKE', ip + delimiter + '%');
|
||||
}
|
||||
|
||||
const rows = await query.select()
|
||||
.distinct('name')
|
||||
.orderBy('time', 'desc')
|
||||
.limit(5);
|
||||
return rows.map(row => row.name);
|
||||
});
|
||||
}
|
||||
|
||||
async getIPsByName(name: string): Promise<Array<string>> {
|
||||
return this.db.runTransaction(async tx => {
|
||||
const rows = await tx.table('aliases')
|
||||
.select('ip')
|
||||
.where({ name });
|
||||
return rows.map(row => row.ip);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export { AliasesDB };
|
||||
Loading…
Add table
Add a link
Reference in a new issue