import { md5 } from "./hash" ; import { Redisearch } from "redis-modules-sdk" ; import * as config from "config" ; import { log } from "./logger" ; export class Database { private client : any ; public constructor ( ) { const port = config . get ( "server.port" ) ; const host = config . get ( "server.host" ) ; this . client = new Redisearch ( { host : host , port : port } ) ; } public async init ( ) { await this . client . connect ( ) ; try { await this . client . create ( "index" , [ "data TEXT" , "timestamp NUMERIC" ] , [ "SORTABLE" , "STOPWORDS 0" ] ) ; } catch ( error ) { if ( error + "" . indexOf ( "Redisearch: ReplyError: Index already exists" ) != 0 ) { log . info ( "No new index created." ) ; } else { log . error ( error ) ; } } } public async save ( data ) { data = data . replace ( /\n/g , " \n" ) ; log . debug ( md5 ( data ) ) ; const p = await this . client . redis . hmset ( [ md5 ( data ) , "data" , data , "timestamp" , + new Date ( ) , ] ) ; this . client . redis . save ( ) ; return p ; } public async search ( query ) { return new Promise < string [ ] > ( ( resolve ) => { query = query . replace ( /:/g , "\\:" ) ; resolve ( this . client . redis . send_command ( "FT.SEARCH" , [ "index" , "@data:(" + query + ")" , "RETURN" , "1" , "data" , "SORTBY" , "timestamp" , ] ) ) ; } ) ; } public async getNoteByHash ( hash ) { return new Promise < string > ( ( resolve ) => { resolve ( this . client . redis . send_command ( "HGET" , [ hash , "data" ] ) ) ; } ) ; } public async deleteNoteByHash ( hash ) { const status = await this . client . redis . send_command ( "DEL" , [ hash ] ) ; if ( status != 1 ) { log . warn ( "Delete did not succeed. Code " + status ) ; } } }