Browse Source

implement redis server start on startup

b3z 6 months ago
parent
commit
b81f670536
5 changed files with 329 additions and 178 deletions
  1. BIN
      .DS_Store
  2. 27 41
      src/database.ts
  3. 150 108
      src/index.ts
  4. 13 9
      src/redisServer.ts
  5. 139 20
      tslint.json

BIN
.DS_Store


+ 27 - 41
src/database.ts

@@ -1,41 +1,37 @@
 import { stringify } from "querystring";
 import { md5 } from "./hash";
-var redis = require('redis');
-
-
+var redis = require("redis");
 
 export class Database {
     private client: any;
-    
+
     constructor() {
         this.client = redis.createClient();
-
-        this.client.on('connect', function () {
-            console.log('connected');
+        this.client.on("connect", function() {
+            console.log("connected to server.");
         });
     }
 
-
     save(data: string): void {
-
         data = data.toLowerCase(); // we don't use case sensitiviy.
 
-        let words: string [] = data.split(' ');
+        let words: string[] = data.split(" ");
         let dataHash = md5(data);
 
         // save doc. With hash reference.
         this.set(dataHash, data);
         // index every word with referencing to hash.
         this.indexing(dataHash, words);
-
     }
 
-    async search(key: string): Promise<string[]> { 
-        return new Promise(async resolve => { // no reject, we just log caught errors.
+    async search(key: string): Promise<string[]> {
+        return new Promise(async resolve => {
+            // no reject, we just log caught errors.
             try {
-                let res: string[] = await this.getList('index:' + key);
+                let res: string[] = await this.getList("index:" + key);
                 resolve(res);
-            } catch (e) { // we log here instead of rejecting the Promise. 
+            } catch (e) {
+                // we log here instead of rejecting the Promise.
                 console.log(e);
             }
         });
@@ -44,7 +40,7 @@ export class Database {
     async resolveHash(hash: string) {
         return await this.getString(hash);
     }
-    
+
     /* write indexes
         hash1 = Hello Paul
         hash2 = Hello World
@@ -52,16 +48,15 @@ export class Database {
         index:hello = hash1, hash2
         index:world = hash2
     */
-    private indexing(dataHash: string, words: string []) {
-        for (let i = 0; i < words.length; i++)
-            this.appendList('index:' + words[i], dataHash);    
+    private indexing(dataHash: string, words: string[]) {
+        for (let i = 0; i < words.length; i++) this.appendList("index:" + words[i], dataHash);
     }
 
     // redis functionalities.
 
     // appends an element to a named list on the right side.
     private appendList(name: string, element: string) {
-        this.client.rpush([name, element], function (err: string, reply: string) {
+        this.client.rpush([name, element], function(err: string, reply: string) {
             console.log(err, reply); //prints 2
         });
     }
@@ -69,7 +64,7 @@ export class Database {
     // async/await solution getList by key - Thank you H1ghBre4k3r
     private async getList(key: string): Promise<string[]> {
         return new Promise((resolve, reject) => {
-            this.client.lrange(key, 0, -1, function (err: string, reply: string[]) {
+            this.client.lrange(key, 0, -1, function(err: string, reply: string[]) {
                 if (err) {
                     reject(err);
                 }
@@ -77,49 +72,41 @@ export class Database {
             });
         });
     }
-    
-    private set(key: string, value: string) {
 
-        if (key == null || key.length == 0)
-            throw new Error("Illegal Argument.")
+    private set(key: string, value: string) {
+        if (key == null || key.length == 0) throw new Error("Illegal Argument.");
 
         this.client.set(key, value, function(err: string, reply: string) {
             console.log(err, reply);
         });
-
     }
     // TODO make this async/await
     private async getString(key: string) {
-        console.log(key)
-        if (!key)
-            throw new Error("Illegal Argument.")
+        console.log(key);
+        if (!key) throw new Error("Illegal Argument.");
 
         return new Promise((resolve, reject) => {
-            this.client.get(key, function (err: string, reply: string) {
+            this.client.get(key, function(err: string, reply: string) {
                 if (err) {
                     reject(err);
                 }
                 resolve(reply);
             });
-        });         
+        });
     }
 
     private delete(key: string): void {
-        if (key == null || key.length == 0)
-            throw new Error("Illegal Argument.")
+        if (key == null || key.length == 0) throw new Error("Illegal Argument.");
 
-        this.client.del(key, function (err: string, reply: string) {
+        this.client.del(key, function(err: string, reply: string) {
             console.log(err, reply);
         });
-
     }
 
     public exists(key: string) {
+        if (key == null || key.length == 0) throw new Error("Illegal Argument.");
 
-        if (key == null || key.length == 0)
-            throw new Error("Illegal Argument.")
-
-        this.client.exists(key, function (err: string, reply: any) {
+        this.client.exists(key, function(err: string, reply: any) {
             if (reply === 1) {
                 return true;
             } else {
@@ -139,7 +126,6 @@ client.hmset('frameworks', {
 
 */
 
-
 /*
 
 if value is of type string -> GET <key>
@@ -148,4 +134,4 @@ if value is of type lists -> lrange <key> <start> <end>
 if value is of type sets -> smembers <key>
 if value is of type sorted sets -> ZRANGEBYSCORE <key> <min> <max>
 
-*/
+*/

+ 150 - 108
src/index.ts

@@ -5,26 +5,25 @@ import { startServer } from "./redisServer";
 //import { Controller } from "./controller"; // this is how we wanna import dude.
 
 let mainWindow: Electron.BrowserWindow;
-let tray = null
+let tray = null;
 let db: Database;
 
-//enable hot reload 
-//require('electron-reload')(__dirname);
-
 function createWindow() {
-  // Create the browser window.
-  mainWindow = new BrowserWindow({
-    height: 600,
-    title: "Information Management System",
-    webPreferences: {
-      nodeIntegration: true, // with this set we have nodeIntegration in index.html. No need to use require.js anymore.
-      preload: path.join(__dirname, "preload.js"),
-    },
-    width: 800,
-  });
-
-  //setup tray
-  /* 
+    const redisServer = startServer(); // spin up redis Server.
+    db = new Database(); // connect with ne db cli.
+
+    // Create the browser window.
+    mainWindow = new BrowserWindow({
+        height: 600,
+        title: "Information Management System",
+        webPreferences: {
+            nodeIntegration: true // with this set we have nodeIntegration in index.html. No need to use require.js anymore.
+        },
+        width: 800
+    });
+
+    //setup tray
+    /* 
   tray = new Tray(path.join(__dirname, "../assets/eg.png"))
   const contextMenu = Menu.buildFromTemplate([
     { label: 'Item1', type: 'radio' },
@@ -35,26 +34,21 @@ function createWindow() {
   tray.setToolTip('Dies ist meine Anwendung.')
   tray.setContextMenu(contextMenu)
 */
-  
-  // and load the index.html of the app.
-  mainWindow.loadFile(path.join(__dirname, "../index.html"));
-  //let c = new Controller(); //?!?! is this how it should be done?
-  
-  // Emitted when the window is closed.
-  mainWindow.on("closed", () => {
-    // Dereference the window object, usually you would store windows
-    // in an array if your app supports multi windows, this is the time
-    // when you should delete the corresponding element.
-    mainWindow = null;
-  });
-
-  const mainMenu = Menu.buildFromTemplate(mainMenuTemplate); //build the actual menu
-  Menu.setApplicationMenu(mainMenu); // insert menu
-
-
-  //after window setup now setup db
-  //startServer(); // spin up redis server.
-  db = new Database(); // connect with ne db cli.
+
+    // and load the index.html of the app.
+    mainWindow.loadFile(path.join(__dirname, "../index.html"));
+    //let c = new Controller(); //?!?! is this how it should be done?
+
+    // Emitted when the window is closed.
+    mainWindow.on("closed", () => {
+        // Dereference the window object, usually you would store windows
+        // in an array if your app supports multi windows, this is the time
+        // when you should delete the corresponding element.
+        mainWindow = null;
+    });
+
+    const mainMenu = Menu.buildFromTemplate(mainMenuTemplate); //build the actual menu
+    Menu.setApplicationMenu(mainMenu); // insert menu
 }
 
 // This method will be called when Electron has finished
@@ -64,62 +58,112 @@ app.on("ready", createWindow);
 
 // Quit when all windows are closed.
 app.on("window-all-closed", () => {
-  // On OS X it is common for applications and their menu bar
-  // to stay active until the user quits explicitly with Cmd + Q
-  if (process.platform !== "darwin") {
-    app.quit();
-  }
+    // On OS X it is common for applications and their menu bar
+    // to stay active until the user quits explicitly with Cmd + Q
+    if (process.platform !== "darwin") {
+        app.quit();
+    }
 });
 
 app.on("activate", () => {
-  // On OS X it"s common to re-create a window in the app when the
-  // dock icon is clicked and there are no other windows open.
-  if (mainWindow === null) {
-    createWindow();
-  }
+    // On OS X it"s common to re-create a window in the app when the
+    // dock icon is clicked and there are no other windows open.
+    if (mainWindow === null) {
+        createWindow();
+    }
 });
 
 //Menu template
-const mainMenuTemplate: any[] = [ // array need to be any so we can add empty object later.
-  {
-    label: app.getName(),
-    submenu: [
-      { label: 'Print Hello', click() { handlePrintHello(); }},
-      { label: 'Quit', accelerator: 'CmdOrCtrl + Q', click() { app.quit(); }}
-    ]
-  },
-  {
-    label: 'Edit',
-    submenu: [
-      { label: 'Save', accelerator: 'CmdOrCtrl + S', click() { handleSave(); }},
-      { label: 'Clear', accelerator: 'CmdOrCtrl + D', click() { handleClear(); }},
-      { type: "separator" },
-      { label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" },
-      { label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" },
-      { type: "separator" },
-      { label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" },
-      { label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" },
-      { label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" },
-      { label: "Select All", accelerator: "CmdOrCtrl+A", selector: "selectAll:" }
-    ]
-  }
+const mainMenuTemplate: any[] = [
+    // array need to be any so we can add empty object later.
+    {
+        label: app.getName(),
+        submenu: [
+            {
+                label: "Print Hello",
+                click() {
+                    handlePrintHello();
+                }
+            },
+            {
+                label: "Quit",
+                accelerator: "CmdOrCtrl + Q",
+                click() {
+                    app.quit();
+                }
+            }
+        ]
+    },
+    {
+        label: "Edit",
+        submenu: [
+            {
+                label: "Save",
+                accelerator: "CmdOrCtrl + S",
+                click() {
+                    handleSave();
+                }
+            },
+            {
+                label: "Clear",
+                accelerator: "CmdOrCtrl + D",
+                click() {
+                    handleClear();
+                }
+            },
+            { type: "separator" },
+            { label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" },
+            { label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" },
+            { type: "separator" },
+            { label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" },
+            { label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" },
+            { label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" },
+            { label: "Select All", accelerator: "CmdOrCtrl+A", selector: "selectAll:" }
+        ]
+    }
 ];
 
 //add developer tools if not in production
-if (process.env.NODE_ENV !== 'production') {
-  mainMenuTemplate.push({
-    label: 'Dev Tools',
-    submenu: [
-      { label: 'Toggle', accelerator: process.platform == 'darwin' ? 'Command+I' : 'Ctrl+I', click() { mainWindow.webContents.openDevTools(); }},
-      { role: 'reload' },
-      { role: 'seperator' },
-      { label: 'Run search', click() { handleSearch() } },
-      { role: 'seperator'},
-      { label: 'Test Status Item', click() { addStatus(undefined, "But here goes text"); } },
-      { label: 'Icon Status Item', click() { addStatus("assets/icons/png/icon.png", undefined); } },
-      { label: 'Clear all Status', click() { clearStatus(); } }
-    ]
-  });
+if (process.env.NODE_ENV !== "production") {
+    mainMenuTemplate.push({
+        label: "Dev Tools",
+        submenu: [
+            {
+                label: "Toggle",
+                accelerator: process.platform == "darwin" ? "Command+I" : "Ctrl+I",
+                click() {
+                    mainWindow.webContents.openDevTools();
+                }
+            },
+            { role: "reload" },
+            { role: "seperator" },
+            {
+                label: "Run search",
+                click() {
+                    handleSearch();
+                }
+            },
+            { role: "seperator" },
+            {
+                label: "Test Status Item",
+                click() {
+                    addStatus(undefined, "But here goes text");
+                }
+            },
+            {
+                label: "Icon Status Item",
+                click() {
+                    addStatus("assets/icons/png/icon.png", undefined);
+                }
+            },
+            {
+                label: "Clear all Status",
+                click() {
+                    clearStatus();
+                }
+            }
+        ]
+    });
 }
 
 /*
@@ -129,8 +173,7 @@ if (process.platform == 'darwin') {
 } 
 */
 function handlePrintHello() {
-  console.log("Hello World!");
-  
+    console.log("Hello World!");
 }
 
 /**
@@ -139,46 +182,45 @@ function handlePrintHello() {
  * @param message which shall eb shown left side of the icon. Put undefined if no message shall be shown.
  */
 function addStatus(iconPath: string, message: string) {
-  mainWindow.webContents.send('statusItem:add', iconPath, message);
+    mainWindow.webContents.send("statusItem:add", iconPath, message);
 }
 
- /**
-  * Clears whole statusBar.
-  */
+/**
+ * Clears whole statusBar.
+ */
 function clearStatus() {
-  mainWindow.webContents.send('statusItem:clear');
+    mainWindow.webContents.send("statusItem:clear");
 }
 
 // should execute js code in index.html so it send the value of the editor back to us.
 function handleSave() {
-  let code = `ipcRenderer.send('item:save', document.querySelector("#editor").value);`
-  mainWindow.webContents.executeJavaScript(code);
+    let code = `ipcRenderer.send('item:save', document.querySelector("#editor").value);`;
+    mainWindow.webContents.executeJavaScript(code);
 }
 
 // catch item:save from editor with the editors value.
-ipcMain.on('item:save', function (e, item) {
-  db.save(item);
+ipcMain.on("item:save", function(e, item) {
+    db.save(item);
 });
 
 // should execute js code in index.html so it send the value of the editor back to us.
 function handleSearch() {
-  let code = `ipcRenderer.send('item:search', document.querySelector("#editor").value);`
-  mainWindow.webContents.executeJavaScript(code);
+    let code = `ipcRenderer.send('item:search', document.querySelector("#editor").value);`;
+    mainWindow.webContents.executeJavaScript(code);
 }
 
 // catch item:search from editor with the editors value.
-ipcMain.on('item:search', async function (e, item) {
-  console.log("Search keyword"+item)
-  let res: string[] = await db.search(item);
+ipcMain.on("item:search", async function(e, item) {
+    console.log("Search keyword" + item);
+    let res: string[] = await db.search(item);
 
-  for (let r in res) {
-    console.log( await db.resolveHash(res[r]));
-  }
+    for (let r in res) {
+        console.log(await db.resolveHash(res[r]));
+    }
 });
 
-
 function handleClear() {
-  // clear console
-  // TODO implement me :(
-  console.log("clear");
-}
+    // clear console
+    // TODO implement me :(
+    console.log("clear");
+}

+ 13 - 9
src/redisServer.ts

@@ -1,12 +1,16 @@
-const RedisServer = require('redis-server');
+const RedisServer = require("redis-server");
 const server = new RedisServer(6379);
 
 export function startServer() {
-  server.open((err: string) => {
-    if (err === null) {
-      console.log('Server ready for connection.');
-    } else {
-      console.log(err);
-    }
-  });
-}
+    const RedisServer = require("redis-server");
+
+    // Simply pass the port that you want a Redis server to listen on.
+    const server = new RedisServer(6379);
+
+    server.open((err: any) => {
+        if (err === null) {
+            // You may now connect a client to the Redis
+            // server bound to port 6379.
+        }
+    });
+}

+ 139 - 20
tslint.json

@@ -1,22 +1,141 @@
 {
-  "extends": "tslint:recommended",
-  "rules": {
-    "max-line-length": {
-      "options": [
-        120
-      ]
-    },
-    "new-parens": true,
-    "no-arg": true,
-    "no-bitwise": true,
-    "no-conditional-assignment": true,
-    "no-consecutive-blank-lines": false
-  },
-  "jsRules": {
-    "max-line-length": {
-      "options": [
-        120
-      ]
+    "extends": ["tslint:recommended", "tslint-config-prettier"],
+    "rules": {
+        "adjacent-overload-signatures": true,
+        "align": [false, "statements"],
+        "array-type": [true, "array"],
+        "arrow-parens": false,
+        "arrow-return-shorthand": [true],
+        "callable-types": false,
+        "class-name": true,
+        "comment-format": [true, "check-space"],
+        "curly": true,
+        "cyclomatic-complexity": [true, 7],
+        "deprecation": {
+            "severity": "warning"
+        },
+        "eofline": true,
+        "forin": true,
+        "indent": [true, "spaces", 4],
+        "import-spacing": true,
+        "interface-name": [true, "never-prefix"],
+        "jsdoc-format": true,
+        "label-position": true,
+        "max-classes-per-file": false,
+        "max-line-length": [false],
+        "member-access": true,
+        "member-ordering": [
+            true,
+            {
+                "order": ["static-field", "static-method", "instance-field", "constructor", "instance-method"]
+            }
+        ],
+        "new-parens": true,
+        "no-angle-bracket-type-assertion": true,
+        "no-any": false,
+        "no-arg": true,
+        "no-bitwise": true,
+        "no-conditional-assignment": true,
+        "no-consecutive-blank-lines": [true, 1],
+        "no-console": [true, "log"],
+        "no-construct": true,
+        "no-debugger": true,
+        "no-duplicate-imports": true,
+        "no-duplicate-super": true,
+        "no-duplicate-switch-case": true,
+        "no-empty": true,
+        "no-eval": true,
+        "no-implicit-dependencies": false,
+        "no-inferrable-types": [true],
+        "no-internal-module": true,
+        "no-misused-new": true,
+        "no-object-literal-type-assertion": true,
+        "no-parameter-properties": true,
+        "no-parameter-reassignment": true,
+        "no-reference": true,
+        "no-reference-import": true,
+        "no-require-imports": false,
+        "no-return-await": true,
+        "no-shadowed-variable": false,
+        "no-string-throw": true,
+        "no-switch-case-fall-through": false,
+        "no-submodule-imports": [true, "text-mask-addons"],
+        "no-trailing-whitespace": [true, "ignore-comments", "ignore-jsdoc", "ignore-template-strings"],
+        "no-unnecessary-class": true,
+        "no-unnecessary-type-assertion": true,
+        "no-unused-expression": true,
+        "no-var-keyword": true,
+        "no-var-requires": true,
+        "number-literal-format": true,
+        "object-literal-key-quotes": [true, "as-needed"],
+        "object-literal-shorthand": true,
+        "one-line": [true, "check-catch", "check-else", "check-finally", "check-open-brace", "check-whitespace"],
+        "object-literal-sort-keys": [false],
+        "one-variable-per-declaration": [true, "ignore-for-loop"],
+        "ordered-imports": [
+            true,
+            {
+                "import-sources-order": "case-insensitive",
+                "named-imports-order": "any"
+            }
+        ],
+        "prefer-const": true,
+        "prefer-for-of": true,
+        "prefer-method-signature": true,
+        "prefer-template": [true, "allow-single-concat"],
+        "quotemark": [true, "double", "jsx-double", "avoid-escape"],
+        "radix": true,
+        "space-before-function-paren": [
+            true,
+            {
+                "anonymous": "never",
+                "named": "never",
+                "asyncArrow": "always",
+                "method": "never",
+                "constructor": "never"
+            }
+        ],
+        "trailing-comma": [
+            true,
+            {
+                "multiline": "never",
+                "singleline": "never"
+            }
+        ],
+        "triple-equals": [true],
+        "typedef": [true, "call-signature", "property-declaration"],
+        "typedef-whitespace": [
+            true,
+            {
+                "call-signature": "nospace",
+                "index-signature": "nospace",
+                "parameter": "nospace",
+                "property-declaration": "nospace",
+                "variable-declaration": "nospace"
+            },
+            {
+                "call-signature": "onespace",
+                "index-signature": "onespace",
+                "parameter": "onespace",
+                "property-declaration": "onespace",
+                "variable-declaration": "onespace"
+            }
+        ],
+        "unified-signatures": true,
+        "use-isnan": true,
+        "variable-name": [true, "ban-keywords", "check-format", "allow-leading-underscore", "allow-pascal-case"],
+        "whitespace": [
+            true,
+            "check-branch",
+            "check-decl",
+            "check-operator",
+            "check-module",
+            "check-separator",
+            "check-rest-spread",
+            "check-type",
+            "check-typecast",
+            "check-type-operator",
+            "check-preblock"
+        ]
     }
-  }
-}
+}