Skip to content

Commit

Permalink
added #10, #11, #12
Browse files Browse the repository at this point in the history
  • Loading branch information
Sv443 committed Jan 25, 2021
1 parent 4debb6e commit f143a6e
Show file tree
Hide file tree
Showing 10 changed files with 295 additions and 2 deletions.
42 changes: 42 additions & 0 deletions SvCoreLib.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as _http from 'http';
import * as _mysql from 'mysql';


//#MARKER functions
Expand Down Expand Up @@ -204,6 +205,24 @@ export function randomItem(array: any[]): any;
*/
export function removeDuplicates(array: any[]): any[];

/**
* 🔹 Inserts values into a percent-formatted string.
* If there are no insertion marks, this function returns the unmodified input string. 🔹
* @param str A string containing numbered insertion marks (%1, %2, ..., %10, %11, ...)
* @param values [Rest parameter] The values to insert into the string - All values that are not of type `string` will be converted using their method `.toString()`
* @throws Throws a "TypeError" if the parameter `str` is not a string or if one of the values could not be converted to a string
* @since 1.12.0
*/
export function insertValues(str: string, ...values: any[]): string;

/**
* 🔹 Sets the terminal window's title. Supports both Windows and *nix. 🔹
* @param title The string to set the window title to
* @throws Throws a "TypeError" if the parameter `title` is not a string and couldn't be converted to one
* @since 1.12.0
*/
export function setWindowTitle(title: string): void;

/**
* 🔸 Offers a few functions to generate seeded random numbers.
* This means using the same input seed, you will always get the same output number, just like you get the same Minecraft world when using the same seed twice. 🔸
Expand Down Expand Up @@ -452,6 +471,23 @@ declare namespace filesystem {
export function readdirRecursiveSync(folder: string): string[];
}

//#SECTION SQL

/**
* 🔸 Offers a few functions to interface with a SQL database 🔸
*/
declare namespace sql {
/**
* 🔹 Sends a formatted (SQLI-protected) query 🔹
* @param connection An SQL connection instantiated with [`mysql.createConnection()`](https://www.npmjs.com/package/mysql#establishing-connections)
* @param query The SQL query with question marks where the inserted values should be
* @param options The options of this query. [Here are the possible properties](https://www.npmjs.com/package/mysql#connection-options) - leave undefined to choose the default options
* @param insertValues [Rest parameter] The values to be inserted into the question marks - use the primitive type `null` for an empty value
* @since 1.12.0
*/
export function sendQuery(connection: _mysql.Connection, query: string, options: _mysql.QueryOptions | undefined, ...insertValues: null[] | string[] | number[]): Promise<object>;
}

//#MARKER classes

/**
Expand Down Expand Up @@ -812,6 +848,12 @@ declare namespace Errors {
* @since 1.12.0
*/
class InvalidMimeTypeError extends Error {}

/**
* 🔹 This error gets thrown when a provided SQL connection was not established or errored out 🔹
* @since 1.12.0
*/
class SqlConnectionNotEstablishedError extends Error {}
}

//#MARKER objects
Expand Down
5 changes: 5 additions & 0 deletions SvCoreLib.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ module.exports = {
randomizeArray: require("./src/functions/randomizeArray"),
randomItem: require("./src/functions/randomItem"),
removeDuplicates: require("./src/functions/removeDuplicates"),
insertValues: require("./src/functions/insertValues"),
setWindowTitle: require("./src/functions/setWindowTitle"),
seededRNG: {
generateSeededNumbers: require("./src/functions/seededRNG/generateSeededNumbers"),
generateRandomSeed: require("./src/functions/seededRNG/generateRandomSeed"),
Expand All @@ -45,6 +47,9 @@ module.exports = {
logger: require("./src/functions/filesystem/logger"),
downloadFile: require("./src/functions/filesystem/downloadFile"),
},
sql: {
sendQuery: require("./src/functions/sql/sendQuery"),
},
Errors: require("./src/classes/Errors"),
pause: require("./src/functions/pause"),
inDebugger: require("./src/functions/inDebugger"),
Expand Down
5 changes: 4 additions & 1 deletion changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@


## 1.12.0
### FolderDaemon Fix
- Added functions
- `sql.sendQuery()` to send SQLI protected queries ([issue #10](https://github.com/Sv443/SvCoreLib/issues/10))
- `insertValues()` to insert values into a percent-formatted string ([issue #11](https://github.com/Sv443/SvCoreLib/issues/11))
- `setWindowTitle()` to set the terminal's window title ([issue #12](https://github.com/Sv443/SvCoreLib/issues/12))
- Fixed bugs
- FolderDaemon didn't work when blacklist pattern array was empty ([issue #6](https://github.com/Sv443/SvCoreLib/issues/6))
- FolderDaemon didn't call onChanged when file was reset to a previously known file content ([issue #7](https://github.com/Sv443/SvCoreLib/issues/7))
Expand Down
120 changes: 120 additions & 0 deletions docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,14 @@ This is the documentation of SvCoreLib (referred to as SCL)
- [seededRNG.generateRandomSeed()](#seededrnggeneraterandomseed)
- [seededRNG.generateSeededNumbers()](#seededrnggenerateseedednumbers)
- [seededRNG.validateSeed()](#seededrngvalidateseed)
- [SQL](#sql)
- [sql.sendQuery()](#sqlsendquery)
- [Other](#other)
- [allEqual()](#allequal)
- [byteLength()](#bytelength)
- [error()](#error)
- [inDebugger()](#indebugger)
- [insertValues](#insertvalues)
- [isArrayEmpty()](#isarrayempty)
- [isEmpty()](#isempty)
- [mapRange()](#maprange)
Expand All @@ -46,6 +49,7 @@ This is the documentation of SvCoreLib (referred to as SCL)
- [removeDuplicates()](#removeduplicates)
- [replaceAt()](#replaceat)
- [reserialize()](#reserialize)
- [setWindowTitle()](#setwindowtitle)
- [softShutdown()](#softshutdown)
- [unused()](#unused)
- [yesShutdown()](#yesshutdown)
Expand Down Expand Up @@ -682,6 +686,62 @@ Seeds in SCL need to be of a certain format. Some other functions in this sectio
<br><br><br>
<!-- #SECTION SQL -->
## SQL
This subsection, accessed with `scl.sql`, offers functions to interface with SQL databases.
These functions depend on the native module [`mysql`](https://www.npmjs.com/package/mysql).
<br><br>
> ### sql.sendQuery()
> Sends a formatted (SQLI-protected) query.
>
> The param `connection` needs to be passed an SQL connection instantiated with [`mysql.createConnection()`](https://www.npmjs.com/package/mysql#establishing-connections)
> The param `query` needs to be passed the SQL query with question marks where the inserted values should be.
> The param `options` needs to be passed an object of options of this query. [Here are the possible properties](https://www.npmjs.com/package/mysql#connection-options) - leave undefined to choose the default options.
> The rest parameter `insertValues` needs to be passed the values to be inserted into the question marks - use the primitive type `null` for an empty value.
>
> The returned promise resolves to an object containing the response from the database or rejects to an error string.
> ```ts
> scl.sql.sendQuery(connection: mysql.Connection, query: string, options?: mysql.QueryOptions, ...insertValues: null | string | number): Promise<object>
> ```
>
> <br><details><summary><b>Example Code - click to show</b></summary>
>
> ```js
> const scl = require("svcorelib");
> const mysql = require("mysql");
>
> let sqlConnection = mysql.createConnection({
> host: "127.0.0.1",
> user: process.env["DB_USERNAME"], // requires setting an environment variable
> password: process.env["DB_PASSWORD"], // ^
> database: "db_name",
> port: 3306
> });
>
> let options = {
> timeout: 2000
> };
>
> let id = 5;
>
>
> scl.sql.sendQuery(sqlConnection, "SELECT * FROM foo WHERE ID = ?", options, id).then(res => {
> console.log(JSON.stringify(res, null, 4));
> }).catch(err => {
> console.error(`Error: ${err}`);
> });
> ```
>
> </details>
<br><br><br>
<!-- #SECTION Other -->
## Other
This subsection, accessed with just `scl`, offers many miscellaneous functions.
Expand Down Expand Up @@ -1040,6 +1100,44 @@ This subsection, accessed with just `scl`, offers many miscellaneous functions.
<br><br><br>
> ### insertValues()
> Inserts values into a preformatted string containing so called insertion marks.
> If there are no insertion marks, this function returns the unmodified input string.
>
> The parameter `str` is a string containing numbered insertion marks in the format `%1`, `%2`, `%10`, `%100`, ...
> The `values` param is a rest parameter containing any values that can be converted to a string.
>
> This function throws a `TypeError` if the parameter `str` is not a string or if one of the values could not be converted to a string.
> ```ts
> insertValues(str: string, ...values: any[]): string;
> ```
>
> <br><details><summary><b>Example Code - click to show</b></summary>
>
> ```js
> class Person {
> constructor(name, age)
> {
> this.name = name;
> this.age = age;
> }
>
> text()
> {
> return scl.insertValues("%1 is %2 years old", this.name, this.age);
> }
> }
>
> let sven = new Person("Sven", 18);
> console.log(sven.text()); // "Sven is 18 years old"
> ```
>
> </details>
<br><br><br>
> ### replaceAt()
> Replaces a character from the specified `string` at the specified `index` with the value of `replacement`
> ```ts
Expand Down Expand Up @@ -1115,6 +1213,28 @@ This subsection, accessed with just `scl`, offers many miscellaneous functions.
<br><br><br>
> ### setWindowTitle()
> Sets the window title of the CLI / terminal.
> This function supports both Windows and *nix.
> ```ts
> scl.setWindowTitle(title: string): void
> ```
>
> <br><details><summary><b>Example Code - click to show</b></summary>
>
> ```js
> const scl = require("svcorelib");
> const packageJson = require("./package.json"); // adjust this path if you're not in the project root dir
>
> scl.setWindowTitle(`${packageJson.name} v${packageJson.version}`);
> ```
>
> </details>
<br><br><br>
> ### softShutdown()
> Executes a synchronous function before the process is exited.
> ```ts
Expand Down
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"minimatch": "^3.0.4"
},
"devDependencies": {
"@types/mysql": "^2.15.17",
"@types/node": "^14.6.0",
"eslint": "^7.7.0"
}
Expand Down
15 changes: 14 additions & 1 deletion src/classes/Errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,24 @@ class InvalidMimeTypeError extends Error {
}
}

class SqlConnectionNotEstablishedError extends Error {
constructor(message)
{
super(message);
this.name = "SQL connection was not established";
this.date = new Date();

if(Error.captureStackTrace)
Error.captureStackTrace(this, SqlConnectionNotEstablishedError);
}
}


module.exports = {
InvalidPathError,
NotAFolderError,
PatternInvalidError,
NoStdinError,
InvalidMimeTypeError
InvalidMimeTypeError,
SqlConnectionNotEstablishedError
};
31 changes: 31 additions & 0 deletions src/functions/insertValues.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
function insertValues(str, ...values)
{
if(typeof str != "string")
throw new TypeError(`Parameter "${str}" is not of type "string" (got "${typeof str}")`);

if(!str.match(/%[0-9]+/g))
return str;

values.forEach((arg, i) => {
let rex = new RegExp(`%${i + 1}`);

if(typeof arg !== "string" && typeof arg.toString == "function")
arg = arg.toString();

if(str.match(rex))
{
try
{
str = str.replace(rex, arg);
}
catch(err)
{
throw new TypeError(`Value "${arg}" at index ${i} could not be inserted: ${err}`);
}
}
});

return str;
}

module.exports = insertValues;
21 changes: 21 additions & 0 deletions src/functions/setWindowTitle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* Sets the terminal window's title (supports Windows and *nix)
* @param {String} title
*/
function setWindowTitle(title)
{
if(typeof title !== "string")
{
if(typeof title.toString == "function")
title = title.toString();
else
throw new TypeError(`Parameter "title" is not of type string (got "${typeof title}")`);
}

if(process.platform != "win32")
process.stdout.write(`\x1b]2;${title}\x1b\x5c`); // *nix doesn't have a "nice" way to set the window title but this escape sequence should be able to do it (for reference search "OSC control sequences" on this page: https://man7.org/linux/man-pages/man4/console_codes.4.html)
else
process.title = title; // This should work only on Windows
}

module.exports = setWindowTitle;
Loading

0 comments on commit f143a6e

Please sign in to comment.