Gathering detailed insights and metrics for @friquet-luca/lazy-portable
Gathering detailed insights and metrics for @friquet-luca/lazy-portable
npm install @friquet-luca/lazy-portable
Typescript
Module System
Node Version
NPM Version
73.2
Supply Chain
100
Quality
75.4
Maintenance
100
Vulnerability
100
License
TypeScript (87.31%)
JavaScript (12.16%)
HTML (0.53%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
71 Commits
1 Watching
2 Branches
2 Contributors
Latest Version
1.0.2
Package Id
@friquet-luca/lazy-portable@1.0.2
Unpacked Size
69.17 kB
Size
16.75 kB
File Count
24
NPM Version
8.11.0
Node Version
16.15.1
Cumulative downloads
Total Downloads
Last day
0%
0
Compared to previous day
Last week
0%
0
Compared to previous week
Last month
0%
0
Compared to previous month
Last year
0%
0
Compared to previous year
1
A NodeJS toolbox made by and for lazy developers.
The source code is available on GitHub and the project on NPM.
To install the lazy toolbox, just enter:
1npm i lazy-toolbox
on your node project.
The project is divided in three different part that could need some dependances:
Client
The client part need to be repack with something like webpack
.
Server
The server dependances are fastify
, ws
and node
.
Shared
The shared part don't need any dependances since it's gonna be either used by the client or the server but will need a repack if it's used for the client.
TypeScript Hotfix: Types are now handled correctly (wrong type path in package.json
corrected).
Development of tools for tracking changes and help development even further.
deleteDirectory
function in LazyFS
.skipChanges
method in LazyWatcher
.db
argument on LazyRouter
's constructor.setDB
method in LazyRouter
.db
argument on LazySocket
's constructor.setDB
method in LazySocket
.watchFiles
when stopped in LazyWatcher
.LazyWatcher
.LazyWatcher
constructor : 2 new arguments for exclusions.stop
in LazyEncapProcess
.start
method when giving output from the server in LazyEncapProcess
.An important update to resolve a bunch of encountered errors for server setup.
loadStaticRoutes
method for LazyRouter
.LazyMath
.index.js
.registerPaths
in LazyRouter
given route.LazyModLoader
require that can sometimes throw an error instead of loading a module.LazyModLoader
that throw an error if the directory to load doesn't exist instead of ignoring the loading.Added a full documentation with example. The documentation is subject to changes and will be up to date on github.
childs
property to HTMLTag
(see LazyDoc
for more infos)..mjs
files support for LazyModLoader
.moduleFolder
of the LazyModLoader
's constructor
set to "./"
.stop
function to LazyWatcher
.
Patches:watchFiles
of LazyWatcher
such that the process can be stopped if needed.LazyHtNetwork
.The initial release of the lazy toolbox.
This part explain all tools with examples if it's needed.
Last update: version: 1.1.1
1function getType(parameter: any): string
Get the type of the parameter, extending typeof
to support class
and array
as native options.
Example:
1const { getType } = require('lazy-toolbox'); 2class Animal { 3 constructor(name) { 4 this.name = name; 5 } 6} 7const x = Animal; 8const y = [ 'a', 'b' ]; 9console.log(getType(x)); // class 10console.log(getType(y)); // array 11// Everything else is the same as typeof
1function dateLog(msg: any): string
Create a message with the time display up to the s.
It will be showned as [HH:MM:SS] MY_MESSAGE
.
Example:
1const { dateLog } = require('lazy-toolbox'); 2console.log(dateLog("Hello world")); // [10:37:12] Hello world
1function dateLogMS(msg: any): string
Create a message with the time display up to the ms.
It will be showned as [HH:MM:SS.DCM] MY_MESSAGE
.
Example:
1const { dateLogMS } = require('lazy-toolbox'); 2console.log(dateLogMS("Hello world")); // [10:37:12.123] Hello world
1class LazyMath { 2 static modulo(a: number, b: number): number; 3 // New on version: 1.1.1 4 static frac(a: number): number; 5 // New on version: 1.1.1 6 static saturate(a: number): number; 7 // New on version: 1.1.1 8 static sum(k: number, n: number, f: (i: number) => number): number; 9 // New on version: 1.1.1 10 static product(k: number, n: number, f: (i: number) => number): number; 11 // New on version: 1.1.1 12 static isPrime(n: number): boolean; 13 // New on version: 1.1.1 14 static step(n: number, x: number): number; 15 // New on version: 1.1.1 16 static lerp(a: number, b: number, t: number): number; 17 // New on version: 1.1.1 18 static unlerp(a: number, b: number, p: number): number; 19 // New on version: 1.1.1 20 static binomialCoefficient(n: number, k: number): number; 21 // New on version: 1.1.1 22 static derivative(x: number, f: (x: number) => number): number; 23 // New on version: 1.1.1 24 static antiDerivative(x: number, f: (x: number) => number, subdivide: number = 1): number; 25 // New on version: 1.1.1 26 static integral(a: number, b: number, f: (x: number) => number, subdivide: number = 1): number; 27}
Add some lazy math that should have been available at first on JS.
Example:
1const { LazyMath } = require('lazy-toolbox');
2// The JS modulo operator violate the property (a + n) mod n = a mod n.
3// So we've implemented a modulo that doesn't violate it.
4// JS modulo = a - ([a / b] * b)
5// where [a / b] is the truncature of a / b.
6// LazyMath.modulo = a - (⌊a / b⌋ * b)
7// where ⌊a / b⌋ is the floor of a / b.
8
9// Positive value have the same answer
10console.log(LazyMath.modulo(4, 3)); // 1
11console.log(4 % 3) // 1
12// The JS modulo problem lies over here.
13console.log(LazyMath.modulo(-4, 3)); // 2
14console.log(-4 % 3); // -1
15
16// Get the leftover to obtain an integer less or equal to n.
17console.log(LazyMath.frac(2.345)); // 0.345
18console.log(LazyMath.frac(-2.345)); // 0.655
19
20// Get a value between 0 and 1
21console.log(LazyMath.saturate(2.345)); // 1
22
23// sum and product are made to handle iterative function for sum and product.
24// 1 + 2 + 3 + 4 = 10
25console.log(LazyMath.sum(1, 4, (i) => i));
26// 1 * 2 * 3 * 4 * 5 = 5! = 120
27console.log(LazyMath.product(1, 5, (i) => i));
28
29// A method to test if a number is prime.
30// It's not an optimal method, it can be slow as hell but you'll be 100% sure it's a prime number.
31console.log(LazyMath.isPrime(7)); // True
32console.log(LazyMath.isPrime(24)); // False
33
34// Return 1 if x is gequal to n, otherwise n.
35console.log(LazyMath.step(0.3, 0.5)); // 0.3
36console.log(LazyMath.step(0.4, 0.5)); // 0.4
37console.log(LazyMath.step(0.5, 0.5)); // 1
38
39// Do a linear interpolation between a and b using the parameter t for the interpolated distance.
40console.log(LazyMath.lerp(1, 3, 0.5)); // 2
41
42// Get the interpolated distance of p on the line from a to b.
43console.log(LazyMath.unlerp(1, 3, 2)); // 0.5
44
45// Compute the number of ways to choose an unordered subset of k elements from a fixed set of n elements.
46console.log(LazyMath.binomialCoefficient(5, 2)); // 10
47
48// Evaluate the derivative of a function f at a point x. d/dx f(x)
49// For this example, we use the function f(x) = x² and evaluate it's derivative at x = 3.
50// The result should be 6 if the approximation was perfect.
51console.log(LazyMath.derivative(3, (x) => { return x * x; })); // 5.921189464667501
52
53// Evaluate the anti-derivative of a function f' at a point x.
54// For this example, we use the function f'(x) = 2x and evaluate it's anti derivative at x = 3.
55// The result should be 9 if the approximation was perfect.
56console.log(LazyMath.antiDerivative(3, (x) => { return 2 * x; })); // 8.819999999999999
57
58// Evaluate the area under the curve of a function f' from a to b.
59// The result should be 15 if the approximation was perfect.
60console.log(LazyMath.integral(1, 4, (x) => { return 2 * x; })); // 14.819999999999997
Last update: version: 1.1.1
1class LazyCaret { 2 static getCaretPosition(txtArea: HTMLTextAreaElement): number; 3 static setCaretPosition(txtArea: HTMLTextAreaElement, position: number): void; 4 static hasSelection(txtArea: HTMLTextAreaElement): boolean; 5 static getSelectedText(txtArea: HTMLTextAreaElement): string; 6 static setSelection(txtArea: HTMLTextAreaElement, start: number, end: number): void; 7 static tabulation(txtArea: HTMLTextAreaElement, tabLength: number = 4, antiTab: boolean = false): void; 8}
A lazy way to handle caret and tabulation on textarea.
Example:
1const { LazyCaret } = require('lazy-toolbox');
2const textArea = document.querySelector('textarea');
3
4// Set the caret to the second position of a textarea
5LazyCaret.setCaretPosition(textArea, 2);
6
7// Get the current caret position
8console.log(LazyCaret.getCaretPosition(textArea));
9
10// Check if the textarea has the selection.
11if(LazyCaret.hasSelection(textArea)) {
12 // Get the selected text on the textarea
13 console.log(LazyCaret.getSelectedText(textArea));
14}
15
16// Set a selection on the textarea.
17LazyCaret.setSelection(textArea, 0, 2);
18
19// Do a tabulation on the textarea
20LazyCaret.tabulation(textArea);
21
22// Do an anti-tabulation on the textarea
23LazyCaret.tabulation(textArea, true);
24
25// By default, there's 4 spaces made for one tabulation.
26// This can be changed for whatever you want
27LazyCaret.tabulation(textArea, false, 2);
1class LazyClient {
2 constructor(host: string, port: number);
3 registerJSONSender(fns: { (f:(packet: string, obj: any) => any): void }[]): void;
4 registerJSONReciever(fns: {[packet:string]: (obj: any, websocket: WebSocket) => void}): void;
5 sendJSON(packet: string, obj: any): void;
6}
A lazy socket client to setup a websocket communication.
Note: You can't use _packet
as property name.
Example:
1const { LazyClient } = require('lazy-toolbox');
2// Create our client handler, listening to the host at a specific port.
3const socketClient = new LazyClient('localhost', 6060);
4// Register an array of all sender functions.
5socketClient.registerJSONSender([
6 (sender) => {
7 const someTextArea = document.querySelector('.someClass');
8 someDiv.addEventListener('keyup', (e) => {
9 e.preventDefault();
10 // Send a packet called newPacket and some value to the server.
11 // This method is given to us by the LazyClient itself
12 // when registering all our sender.
13 sender('newPacket', {
14 prop: "some value",
15 prop2: 1010
16 });
17 });
18 }
19]);
20// Register a packet as key and a function as value.
21// Whenever the sever send a packet contained in the keys,
22// it will trigger the function associated with it.
23socketClient.registerJSONReciever({
24 // Create a receiver that will execute a function everytime
25 // the server send a packet called message.
26 'message': (data) => {
27 console.log(JSON.stringify(data)); // Show the data received
28 },
29 // Create a receiver that will execute a function everytime
30 // the server send a packet called uwu.
31 'uwu': () => { console.log("owo"); }
32});
33// Send a packet called newPacket to the server with a bunch of values.
34socketClient.sendJSON('newPacket', {
35 prop: "some value",
36 prop2: 1010
37});
1interface HTMLTag { 2 tag: string; 3 id?: string; 4 class?: string[]; 5 // New on version: 1.1.0 6 childs?: HTMLElement[]; 7 attributes?: {[name: string]: string}; 8 eventListeners?: {[name: string]: (e: Event)=>void}; 9} 10class LazyDoc { 11 static newTag(element: HTMLTag): HTMLElement; 12}
A lazy way to write document.something
.
Example:
1const { LazyDoc } = require('lazy-toolbox');
2// document.createElement makes dev cry a lot.
3// It's just an easy way to make it work.
4// It could look ugly, but useful for a lot of cases.
5const newDiv = LazyDoc.newTag({
6 // The HTML element tag name
7 tag: 'div',
8 // Set the id
9 id: 'uwu',
10 // Set some classes
11 class: [
12 'className',
13 'anotherClassName'
14 ],
15 // Add some childs if we want
16 childs: [
17 LazyDoc.newTag({tag: 'p'})
18 ],
19 // Set some attributes
20 attributes: {
21 'value': '0',
22 'owo': 'uwu'
23 },
24 // Add some event listener if needed
25 eventListeners: {
26 'click': (e) => {
27 console.log("Clicked on div!");
28 }
29 }
30});
31/*
32Same as creating the element:
33<div id="uwu" class="className anotherClassName" value="0" owo="uwu">
34 <p></p>
35</div>
36*/
1class LazyHtNetwork { 2 // Last update at version: 1.1.0 3 static async post(path: string, datas: {[name: string]: any}, execute: (json: Promise<any>) => void = (e) => { }, error: (e: any) => void = (e: any) => console.error(e)): Promise<void>; 4 // Last update at version: 1.1.0 5 static async postJSON(path: string, datas: {[name: string]: any}, execute: (json: Promise<any>) => void = (e) => { }, error: (e: any) => void = (e: any) => console.error(e)): Promise<void>; 6 // Last update at version: 1.1.0 7 static async getJSON(path: string, execute: (json: Promise<any>) => void = (e) => { }, error = (e: any) => console.error(e)): Promise<void>; 8}
A lazy way to handle JS fetch API.
Example:
1// Everything in LazyHtNetwork is async, take that into account.
2const { LazyHtNetwork } = require('lazy-toolbox');
3// Post form datas (for PHP as example)
4// Takes a callback from the server for anything.
5LazyHtNetwork.post('http://somewhere.com/somethingToPost/', {
6 'username': document.querySelector('.someInput').value
7}, (json) => { // Server gave us datas back
8 console.log(JSON.stringify(json));
9});
10
11// LazyHtNetwork.postJSON work the same but only post a .json file at the end, not an HTML form.
12// It can't send picture or whatever blob datas could be needed.
13
14// Get a JSON file somewhere.
15LazyHtNetwork.getJSON('http://somewhere.com/jsonFileToGet/', (json) => {
16 console.log(JSON.stringify(json)); // The json we got.
17});
1class LazyView { 2 static replaceInsert(actualElement: HTMLElement, targetElement: string, newHTMLContent: string): void; 3 static inject(htmlDoc: string, toInject: {[name: string]: string}): string; 4 static toNode(content: string): ChildNode | null; 5 static toNodeList(content: string): NodeListOf<ChildNode>; 6 static toArray(content: string): ChildNode[]; 7 static toText(content: ChildNode[]): string; 8}
A bunch of lazy ways to handle some HTML injection or extraction.
Example:
index.html
:
1<div class="someDiv"> 2 <h1>A title<h1> 3 <p>Some text 4 <insert data="replaceUseless"> 5 Some HTML comments. 6 <h2>YES A COMMENT !!! ... kinda.</h2> 7 </insert> 8 </p> I guess. 9</div>
main.js
:
1const { LazyView } = require('lazy-toolbox');
2const testView = document.querySelector('.someDiv');
3LazyView.inject(testView, // Replace all insert[data='targetElement']
4'replaceUseless', // Data to replace
5'was replaced <span>!!</span>' // HTML to inject
6);
7/*
8Result:
9<div class="someDiv">
10 <h1>A title<h1>
11 <p>Some text
12 was replaced <span>!!</span>
13 </p> I guess.
14</div>
15*/
16const result = LazyView.inject(testView.innerHTML, {
17 'replaceUseless': 'was replaced <span>!!</span>'
18}); // Same as before, but instead of modifying the DOM, we just
19// get the HTML string back.
20
21// Create a single child node from an HTML string.
22const pTag = LazyView.toNode('<p>Hello world</p>');
23document.body.appendChild(pTag);
24
25// Create a bunch of child nodes from an HTML string.
26const multiTag = LazyView.toNodeList('<p>Hello world2</p><p>Hello world 3</p>');
27for(let tag of [...multiTag]) {
28 document.body.appendChild(tag);
29}
30
31// Create a bunch of child nodes in an array from an HTML string.
32// It's the equivalent of the previous [...multiTag].
33const multiTagArray = LazyView.toArray('<p>Hello world2</p><p>Hello world 3</p>');
34
35// Convert an array of child nodes back to an HTML string.
36const multiTagArrayHTMLBack = LazyView.toText(multiTagArray);
1class LazyTheme { 2 constructor(themesClasses: string[], elementsQueries: string[]); 3 theme(): string; 4 setNextTheme(): void; 5 setPreviousTheme(): void; 6 setTheme(): void; 7 useTheme(newTheme: string): void; 8}
A lazy theme implementation. It takes a bunch of theme names that will be used as HTML class having the same name. It's useful to handle multiple theme with CSS without having the need to manually implement anything to handle theme other than specifying it's changes.
Example:
1const { LazyTheme } = require('lazy-toolbox'); 2const myThemes = new LazyTheme( 3 [ // Themes class name 4 'light', 5 'dark', 6 'azure' 7 ], 8 [ // Queries for elements to be modified 9 'body', 10 '.myDiv', 11 '.myUserTmp' 12 ] 13); 14myThemes.setTheme(); // Use the theme, the default theme is light here since it's the first element in the theme array. 15console.log(myThemes.theme()); 16 17myThemes.setNextTheme(); // Set the next element in the array, dark, as default theme to be used. 18console.log(myThemes.theme()); 19 20myThemes.setNextTheme(); // Set azure as next element 21console.log(myThemes.theme()); 22 23myThemes.setNextTheme(); // Set light as next element since there's no element after aruze. The array is looped. 24console.log(myThemes.theme()); 25 26// setPreviousTheme() has the same behaviour. 27 28myThemes.useTheme('dark'); // Set the current theme to dark 29console.log(myThemes.theme()); 30 31myThemes.useTheme('omega'); // Set the current theme to light since omega isn't a valid theme 32console.log(myThemes.theme());
Last update: version: 1.1.2
1class LazyModLoader { 2 // Last update at version: 1.1.0 3 constructor(root: string, moduleFolder: string = "./"); 4 load(): {[filePath: string]: any}; 5 static isClass(v: any): boolean; 6 static isFunction(v: any): boolean; 7 static isArray(v: any): boolean; 8 static isObject(v: any): boolean; 9 static isScalar(v: any): boolean; 10}
A module loader to load modules inside a directory.
It loads all .js
files. and .mjs
files as modules.
Example:
myModule.js
:
1module.exports = (name) => { 2 console.log(`Hello ${name}.`); 3};
subMod/mySubModule.js
:
1class MyClass { 2 constructor(name) { 3 this.name = name; 4 this.hello(); 5 } 6 hello() { 7 console.log(`Hello ${this.name}.`); 8 } 9} 10module.exports = MyClass;
main.js
:
1const { LazyModLoader } = require('lazy-toolbox');
2// Create a module loader.
3const modLoader = new LazyModLoader(__dirname, './');
4// Load all modules
5const loadedMods = modLoader.load();
6// Get all modules relative path without the extension
7for(let loadedMod in loadedMods) {
8 // Get the actual module
9 const actualLoadedMod = loadedMods[loadedMod];
10 // Check if the module is a class
11 if(LazyModLoader.isClass(actualLoadedMod)) {
12 // Do something with the class
13 const newMod = new actualLoadedMod('test');
14 }
15 // Check if the module is a function
16 else if(LazyModLoader.isFunction(actualLoadedMod)) {
17 // Do something with the function
18 actualLoadedMod('test');
19 }
20}
1class LazyFS { 2 static getAllInDir(p: string, a: string[] = []): string[]; 3 static getAllFilesInDir(p: string): string[]; 4 static getAllDirsInDir(p: string): string[]; 5 // New on version: 1.1.2 6 static deleteDirectory(directoryPath: string): void; 7 // New on version: 1.1.2 8 static delete(anyPath: string): void; 9}
A lazy file stream for some lazy recursive functions.
Example:
File explorer
:
1- Root 2 - FolderA 3 - FolderC 4 - script.js 5 - FolderB 6 - file.exe
main.js
:
1const { LazyFS } = require('lazy-toolbox'); 2// Get everything inside a directory 3const everything = LazyFS.getAllInDir(__dirname); 4/* Result: 5C:\Somewhere\...\Root\FolderA 6C:\Somewhere\...\Root\FolderA\FolderC 7C:\Somewhere\...\Root\FolderA\script.js 8C:\Somewhere\...\Root\FolderB 9C:\Somewhere\...\Root\file.exe 10*/ 11for(let path of everything) { 12 console.log(path); 13} 14// Get all files inside a directory 15const files = LazyFS.getAllFilesInDir(__dirname); 16/* Result: 17C:\Somewhere\...\Root\FolderA\script.js 18C:\Somewhere\...\Root\file.exe 19*/ 20for(let path of files) { 21 console.log(path); 22} 23// Get all directories inside a directory 24const directories = LazyFS.getAllFilesInDir(__dirname); 25/* Result: 26C:\Somewhere\...\Root\FolderA 27C:\Somewhere\...\Root\FolderA\FolderC 28C:\Somewhere\...\Root\FolderB 29*/ 30for(let path of directories) { 31 console.log(path); 32} 33// Delete the current directory, it's files and all it's sub-directories and sub-files. 34LazyFS.deleteDirectory(__dirname); 35// LazyFS.delete has the same behaviour as LazyFS.deleteDirectory 36// except that LazyFS.delete don't care if it's a file or a directory it 37// needs to remove.
1interface FileEvent { 2 file: string; 3 eventType: string; 4} 5class LazyWatcher { 6 constructor(root: string, timeout: number = 200, excludePaths: string[] = [], excludeEventTypes: string[] = []); 7 checkFileChanges(): FileEvent[]; 8 // Last update at version: 1.1.0 9 async watchFiles(fn: (events: FileEvent[]) => Promise<void>): Promise<void>; 10 // New on version: 1.1.0 11 // Last update at version: 1.1.2 12 stop(): void; 13 // New on version: 1.1.2 14 skipChanges(): void; 15}
A lazy watcher that will watch files by not relying on fs.watch
instability but instead on a timeout approach.
Example:
manualWatcher.js
:
1const { LazyWatcher } = require('lazy-toolbox'); 2// Create a watcher, watching our directory 3const newWatcher = new LazyWatcher(__dirname); 4// Set a timeout to check any changes in the next minute. 5setTimeout(() => { 6 // Check every changes 7 const changes = newWatcher.checkFileChanges(); 8 for(let changeEvent of changes) { 9 console.log(`Event ${changeEvent.eventType} occured on: ${changeEvent.file}`); 10 } 11}, 60000); // Check changes after a minutes.
timeoutWatcher.js
:
1const { LazyWatcher } = require('lazy-toolbox'); 2// Create a watcher, watching our directory with a timeout of 10s. 3const newWatcher = new LazyWatcher(__dirname, 10000); 4// Create a counter, just to show a use case of stop function 5let i = 0; 6// It will trigger every event that occured the next 10s, then it will wait again until it need to check for changes. 7newWatcher.watchFiles(async (changes) => { 8 if(i >= 10) { 9 // Stop the watcher. 10 newWatcher.stop(); 11 } 12 // Show all events: 13 for(let changeEvent of changes) { 14 console.log(`Event ${changeEvent.eventType} occured on: ${changeEvent.file}`); 15 } 16 i++; 17 // If you created some files in this function, it would have been useful to use 18 // newWatcher.skipChanges(); 19 // So the watcher would just skip all your newly made files or modifications 20 // for the next watch. 21});
1class LazyNetList { 2 static internalIPv4(): string[]; 3 static externalIPv4(): string[]; 4 static IPv4(): string[]; 5}
A lazy way to access some network interfaces.
Example:
1const { LazyNetList } = require('lazy-toolbox'); 2// Get all IP v4 inside an array 3const IPs = LazyNetList.IPv4(); 4// Get all internal IP v4 inside an array 5const iIPs = LazyNetList.internalIPv4(); 6// Get all external IP v4 inside an array 7const eIPs = LazyNetList.externalIPv4();
1class LazyEncapProcess { 2 constructor(root: string, processPath: string, logInfo: boolean = true, showDates: boolean = true); 3 // Last update at version: 1.1.2 4 async start(): Promise<void>; 5 // Last update at version: 1.1.2 6 async stop(): Promise<void>; 7}
A lazy way to encapsulate a node process.
Example:
1const { LazyEncapProcess } = require('lazy-toolbox'); 2// Create a node process with the script `server.js`. 3// By default, we get back on the console everything that happened on this node. 4const newNodeProcess = new LazyEncapProcess(__dirname, 'server.js'); 5// Run the script in the background. 6newNodeProcess.start();
1class LazyRouter { 2 // Last update at version: 1.1.2 3 constructor(host: string, port: number, root: string, assetDir: string, db: any = undefined); 4 async loadAssets(): Promise<void>; 5 // Last update at version: 1.1.1 6 async registerPaths(routesFolder: string): Promise<void>; 7 // New on version: 1.1.1 8 async loadStaticRoutes(route: string, staticDirectory: string): Promise<void> 9 start(): void; 10 // New on version: 1.1.2 11 setDB(db: any): void; 12}
A lazy routing setup for lazy people based on fastify
and @fastify/static
.
Example:
File explorer
:
1- Root 2 - public 3 - assets 4 - img.png 5 - routes 6 - customRoute.js 7 - app.js
app.js
:
1const path = require('path'); 2const { LazyRouter } = require('lazy-toolbox'); 3// A little setup to make it async while loading all ours things. 4const setupRouter = async () => { 5 // Set a new router on the localhost, listening on port 3000. 6 // The assets directory will be the static asset directory of the server. 7 const newRouter = new LazyRouter('localhost', 3000, __dirname, './public/assets'); 8 // Load all assets static routes. 9 // Note: The route name will always be ./assets/ on the server side. 10 // localhost:3000/assets/ 11 // It's the equivalent of : 12 // await this.loadStaticRoutes('/assets/', './public/assets'); 13 await newRouter.loadAssets(); 14 // Load all custom routes modules inside the routes folder 15 await newRouter.registerPaths('./routes'); 16 // Registered routes: 17 // localhost:3000/customRoute 18 newRouter.start(); 19} 20// Let's just run this. 21setupRouter();
routes/customRoute.js
:
1// Get the folder relative path as route 2module.exports = (route, fastify, db) => { 3 // A simple implementation for lazyness incarned. 4 fastify.get(route, async (request, reply) => { 5 // Setup your fastify route. 6 }); 7}
1interface FolderMods { 2 onConnect: string; 3 onMessages: string; 4 onDisconnect: string; 5} 6interface LazyClient { 7 id: number; 8} 9class LazySocket { 10 // Last update at version: 1.1.2 11 constructor(port: number, root: string, paths: FolderMods = { onConnect:'./onConnect', onMessages: './onMessages', onDisconnect: './onDisconnect' }, logInfo: boolean = true, showDates: boolean = true, db: any = undefined); 12 connect(): void; 13 sendToAll(packet: string, data: any): void; 14 sendToAllExceptSender(packet: string, socket: WebSocket.WebSocket, data: any): void; 15 clientCount(): number; 16 getClient(socket: WebSocket.WebSocket): LazyClient; 17 getServer(): WebSocket.Server<WebSocket.WebSocket>; 18 static sendToClient(packet: string, socket: WebSocket.WebSocket, data: any): void; 19 static closeClient(socket: WebSocket.WebSocket): void; 20 // New on version: 1.1.2 21 setDB(db: any): void; 22}
A lazy socket implementation to handle websocket.
All the logic lies inside three folders that you can choose.
Functions are gonna be executed depending on the packet name given by a LazyClient
.
Example:
File explorer
:
1- Root 2 - onConnect 3 - connect.js 4 - onMessages 5 - test_msg.js 6 - onDisconnect 7 - disconnect.js 8 - app.js
app.js
1const { LazySocket } = require('lazy-toolbox'); 2// Create a websocket on port 6060 3const socketServer = new LazySocket(6060, __dirname); 4// Start all connections 5socketServer.connect();
onConnect/connect.js
1// Executed whenever a client connect to the server. 2module.exports = (server, clientSocket, db) => { 3 // Do something when a client connect to the server. 4};
onMessages/test_msg.js
1// This packet name is: test_msg
2// If it was inside a folder called myFolder, then the
3// packet would be called: myFolder/test_msg
4module.exports = (server, clientSocket, data, db) => {
5 // Send a packet from the server to all clients.
6 server.sendToAll('message_for_all', {
7 author: data.author,
8 msg: data.msg
9 });
10};
onDisconnect/disconnect.js
1// Executed whenever a client disconnect from the server. 2module.exports = (server, clientSocket, db) => { 3 // Do something if a client disconnect from the server. 4};
No vulnerabilities found.
No security vulnerabilities found.