├── LICENSE ├── README.md ├── clients ├── Nodejs │ └── database_client.js └── Python │ └── database_client.py ├── documentation ├── en │ └── README.md └── es │ └── README.md ├── index.js ├── json-db-manager └── json-db-manager.js └── package.json /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 10 | 11 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 12 | 13 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 14 | 15 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 16 | 17 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 18 | 19 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 20 | 21 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 22 | 23 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 24 | 25 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 26 | 27 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 28 | 29 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 30 | 31 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 32 | 33 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 34 | 35 | (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and 36 | 37 | (b) You must cause any modified files to carry prominent notices stating that You changed the files; and 38 | 39 | (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 40 | 41 | (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 42 | 43 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 44 | 45 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 46 | 47 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 48 | 49 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 50 | 51 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 52 | 53 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 54 | 55 | END OF TERMS AND CONDITIONS 56 | 57 | APPENDIX: How to apply the Apache License to your work. 58 | 59 | To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. 60 | 61 | Copyright [yyyy] [name of copyright owner] 62 | 63 | Licensed under the Apache License, Version 2.0 (the "License"); 64 | you may not use this file except in compliance with the License. 65 | You may obtain a copy of the License at 66 | 67 | http://www.apache.org/licenses/LICENSE-2.0 68 | 69 | Unless required by applicable law or agreed to in writing, software 70 | distributed under the License is distributed on an "AS IS" BASIS, 71 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 72 | See the License for the specific language governing permissions and 73 | limitations under the License. 74 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JsonFlux 2 | 3 | JsonFlux is a lightweight, real-time JSON database system with Socket.IO integration. It offers a flexible and efficient solution for applications requiring quick data operations and live updates. 4 | 5 | ## Key Features: 6 | 7 | - 🚀 Real-time data synchronization via Socket.IO 8 | - 📦 Simple JSON-based data storage 9 | - 🔄 CRUD operations with intuitive API 10 | - 🌐 Cross-platform support (Node.js server, Python & Node.js clients) 11 | - 🛠 Easy model creation and management 12 | - 🔍 Basic query capabilities 13 | - 🔌 Plug-and-play setup for quick prototyping 14 | 15 | ## Documentation: 16 | 17 | You can find the documentation [here](https://github.com/devfastproject/JsonFlux/blob/main/documentation/en/README.md) 18 | 19 | Ideal for small to medium-sized projects, prototypes, and applications where traditional databases might be overkill. JsonFlux combines the simplicity of JSON with the power of real-time communication, making it perfect for dynamic web applications, IoT projects, or any scenario requiring fast, flexible data management. 20 | 21 | Get started with JsonFlux and experience the fluidity of real-time JSON data handling! 22 | 23 | ### 📬 Contact 24 | 25 | For more information about our services or for collaborations, do not hesitate to contact us through our GitHub profile or our official support profile on [Telegram](https://t.me/DevFast_Support). 📧 26 | 27 | -------------------------------------------------------------------------------------- 28 | 29 | JsonFlux es un sistema de base de datos JSON ligero y en tiempo real con integración de Socket.IO. Ofrece una solución flexible y eficiente para aplicaciones que requieren operaciones de datos rápidas y actualizaciones en vivo. 30 | 31 | ## Características principales: 32 | 33 | - 🚀 Sincronización de datos en tiempo real a través de Socket.IO 34 | - 📦 Almacenamiento de datos simple basado en JSON 35 | - 🔄 Operaciones CRUD con API intuitiva 36 | - 🌐 Soporte multiplataforma (servidor Node.js, clientes Python y Node.js) 37 | - 🛠 Fácil creación y gestión de modelos 38 | - 🔍 Capacidades básicas de consulta 39 | - 🔌 Configuración plug-and-play para prototipado rápido 40 | 41 | ## Documentación: 42 | 43 | Puedes encontrar la documentación [aquí](https://github.com/devfastproject/JsonFlux/blob/main/documentation/es/README.md) 44 | 45 | Ideal para proyectos pequeños y medianos, prototipos y aplicaciones donde las bases de datos tradicionales podrían ser excesivas. JsonFlux combina la simplicidad de JSON con el poder de la comunicación en tiempo real, haciéndolo perfecto para aplicaciones web dinámicas, proyectos de IoT o cualquier escenario que requiera una gestión de datos rápida y flexible. 46 | 47 | ¡Comienza con JsonFlux y experimenta la fluidez del manejo de datos JSON en tiempo real! 48 | 49 | ### 📬 Contacto 50 | 51 | Para obtener más información sobre nuestros servicios o colaboraciones, no dude en contactarnos a través de nuestro perfil de GitHub o nuestro perfil de soporte oficial en [Telegram](https://t.me/DevFast_Support). 📧 52 | 53 | -------------------------------------------------------------------------------- 54 | 55 | ![github-contribution-grid-snake](https://user-images.githubusercontent.com/106864876/179424426-29262e35-ab7b-4701-8ce3-8ed7db3d592b.svg) 56 | -------------------------------------------------------------------------------- /clients/Nodejs/database_client.js: -------------------------------------------------------------------------------- 1 | const io = require('socket.io-client'); 2 | 3 | class DatabaseClient { 4 | constructor(url) { 5 | this.socket = io(url); 6 | this.connected = false; 7 | } 8 | 9 | connect() { 10 | return new Promise((resolve, reject) => { 11 | this.socket.on('connect', () => { 12 | console.log('Conectado al servidor'); 13 | this.connected = true; 14 | resolve(); 15 | }); 16 | this.socket.on('connect_error', (error) => { 17 | console.error('Error de conexión:', error); 18 | reject(error); 19 | }); 20 | }); 21 | } 22 | 23 | disconnect() { 24 | return new Promise((resolve) => { 25 | this.socket.disconnect(); 26 | this.socket.on('disconnect', () => { 27 | console.log('Desconectado del servidor'); 28 | this.connected = false; 29 | resolve(); 30 | }); 31 | }); 32 | } 33 | 34 | DB(operation, params) { 35 | return new Promise((resolve, reject) => { 36 | if (!this.connected && operation !== 'connect') { 37 | reject(new Error('No conectado al servidor')); 38 | return; 39 | } 40 | 41 | this.socket.emit(operation, JSON.stringify(params)); 42 | this.socket.once('response', (data) => { 43 | resolve(JSON.parse(data)); 44 | }); 45 | }); 46 | } 47 | } 48 | 49 | const Types = { 50 | NUMBER: "Number", 51 | BOOLEAN: "Boolean", 52 | STRING: "String", 53 | OBJECT: "Object", 54 | ARRAY: "Array", 55 | }; 56 | 57 | module.exports = { DatabaseClient, Types }; 58 | -------------------------------------------------------------------------------- /clients/Python/database_client.py: -------------------------------------------------------------------------------- 1 | import socketio 2 | import json 3 | import asyncio 4 | from loguru import logger 5 | 6 | sio = socketio.AsyncClient() 7 | connected = False 8 | 9 | 10 | async def connect(url): 11 | global connected 12 | if not connected: 13 | logger.info(f"Conectando a {url}...") 14 | await sio.connect(url) 15 | connected = True 16 | logger.warning("Conectado al servidor") 17 | 18 | 19 | async def disconnect(): 20 | global connected 21 | if connected: 22 | logger.info("Desconectando del servidor...") 23 | await sio.disconnect() 24 | connected = False 25 | logger.warning("Desconectado del servidor") 26 | 27 | 28 | async def execute(operation, **kwargs): 29 | global connected 30 | if not connected: 31 | logger.error("No conectado al servidor") 32 | raise Exception("Not connected to server") 33 | 34 | params = json.dumps(kwargs) 35 | future = asyncio.get_event_loop().create_future() 36 | 37 | @sio.on("response") 38 | def on_response(data): 39 | logger.debug(f"Respuesta recibida: {data}") 40 | future.set_result(json.loads(data)) 41 | 42 | logger.info(f"Enviando operación {operation} con parámetros: {params}") 43 | await sio.emit(operation, params) 44 | return await future 45 | 46 | 47 | Types = { 48 | "NUMBER": "Number", 49 | "BOOLEAN": "Boolean", 50 | "STRING": "String", 51 | "OBJECT": "Object", 52 | "ARRAY": "Array", 53 | } 54 | -------------------------------------------------------------------------------- /documentation/en/README.md: -------------------------------------------------------------------------------- 1 | # JSON Database Project Documentation 2 | 3 | ## Overview 4 | 5 | This project implements a JSON database system with a server and clients in Python and Node.js. It uses Socket.IO for real-time communication between the server and clients. 6 | 7 | ## Project Components 8 | 9 | 1. Server (Node.js) 10 | 2. Python Client 11 | 3. Node.js Client 12 | 13 | ## 1. Server 14 | 15 | ### Technologies Used 16 | 17 | - Node.js 18 | - Express 19 | - Socket.IO 20 | - json-db-manager (custom module for handling JSON database) 21 | 22 | ### Main Functionalities 23 | 24 | - Handling Socket.IO connections 25 | - CRUD operations on JSON database 26 | - HTTP endpoints for database operations 27 | 28 | ### Supported Operations 29 | 30 | 1. `addModel`: Adds a new model to the database 31 | 2. `create`: Creates a new document in a specific model 32 | 3. `find`: Search for documents in a model or get all documents in a model if only the name is specified 33 | 4. `update`: Updates an existing document 34 | 5. `destroy`: Deletes a document 35 | 6. `dropModel`: Deletes an entire model 36 | 37 | ### Configuration 38 | 39 | The server can be configured using command-line arguments: 40 | 41 | ``` 42 | node server.js --port 3030 --logs true --autosave 15000 43 | ``` 44 | 45 | ## 2. Python Client 46 | 47 | ### Technologies Used 48 | 49 | - Python 50 | - python-socketio 51 | 52 | ### Main Class: `DatabaseClient` 53 | 54 | #### Methods 55 | 56 | - `connect()`: Connects to the server 57 | - `disconnect()`: Disconnects from the server 58 | - `DB(action, **kwargs)`: Main method for performing database operations 59 | 60 | ### Basic Usage 61 | 62 | ```python 63 | import asyncio 64 | from database_client import execute, Types, connect, disconnect 65 | 66 | 67 | async def main(): 68 | # Conectar 69 | await connect("http://127.0.0.1:3030") 70 | 71 | # Añadir un modelo 72 | model_data = { 73 | "name": { 74 | "type": Types["STRING"], # La key "name" debe ser tipo String 75 | "allowNull": False, # La ley "name" no debe ser nulo al crearse un nuevo usuario 76 | "unique": True, # La key "name" debe ser único para cada usuario, no se puede repetir 77 | }, 78 | "age": { 79 | "type": Types["NUMBER"], 80 | "allowNull": False, 81 | "unique": True, 82 | }, 83 | "isActive": { 84 | "type": Types["BOOLEAN"], 85 | "allowNull": False, 86 | "unique": True, 87 | }, 88 | } 89 | await execute("addModel", name="UserTest", data=model_data) 90 | 91 | # Crear un documento 92 | user_data = {"name": "John Doe", "age": 30, "isActive": True} 93 | await execute("create", name="UserTest", data=user_data) 94 | 95 | # Buscar documentos 96 | result = await execute( 97 | "find", name="UserTest", param="name", equal="John Doe", number=1 98 | ) 99 | 100 | # Actualizar un documento 101 | if result: 102 | print("Se ejecutó") 103 | await execute("update", name="UserTest", last_search=result, data={"age": 31}) 104 | else: 105 | await execute( 106 | "update", 107 | name="UserTest", 108 | search={"param": "name", "value": "John Doe"}, 109 | data={"age": 31}, 110 | ) 111 | 112 | # Eliminar un documento 113 | await execute( 114 | "destroy", name="UserTest", search={"param": "name", "value": "John Doe"} 115 | ) 116 | 117 | # Eliminar un modelo 118 | await execute("dropModel", name="UserTest") 119 | 120 | # Desconectar 121 | await disconnect() 122 | 123 | 124 | asyncio.run(main()) 125 | ``` 126 | 127 | ## 3. Node.js Client 128 | 129 | ### Technologies Used 130 | 131 | - Node.js 132 | - socket.io-client 133 | 134 | ### Main Class: `DatabaseClient` 135 | 136 | #### Methods 137 | 138 | - `connect()`: Connects to the server 139 | - `disconnect()`: Disconnects from the server 140 | - `DB(action, params)`: Main method for performing database operations 141 | 142 | ### Basic Usage 143 | 144 | ```javascript 145 | const { DatabaseClient, Types } = require('./database_client'); 146 | 147 | const client = new DatabaseClient('http://127.0.0.1:3030'); 148 | 149 | async function example() { 150 | try { 151 | await client.connect(); 152 | 153 | // Añadir un modelo 154 | const modelData = { 155 | name: { 156 | type: Types.STRING, 157 | allowNull: false, 158 | unique: true 159 | }, 160 | age: { 161 | type: Types.NUMBER, 162 | allowNull: false, 163 | unique: false 164 | }, 165 | isActive: { 166 | type: Types.BOOLEAN, 167 | allowNull: false, 168 | unique: false 169 | } 170 | }; 171 | await client.DB('addModel', { name: "User", data: modelData }); 172 | 173 | // Crear un documento 174 | const userData = { name: "John Doe", age: 30, isActive: true }; 175 | await client.DB('create', { name: "User", data: userData }); 176 | 177 | // Buscar documentos 178 | const result = await client.DB('find', { name: "User", param: "name", equal: "John Doe", number: 1 }); 179 | console.log(result); 180 | 181 | // Actualizar un documento 182 | if (result) { 183 | await client.DB('update', { 184 | name: "User", 185 | last_search: result, 186 | data: { age: 31 } 187 | }); 188 | } else { 189 | await client.DB('update', { 190 | name: "User", 191 | search: { param: "name", value: "John Doe" }, 192 | data: { age: 31 } 193 | }); 194 | } 195 | 196 | // Eliminar un documento 197 | await client.DB('destroy', { 198 | name: "User", 199 | search: { param: "name", value: "John Doe" } 200 | }); 201 | 202 | // Eliminar un modelo 203 | await client.DB('dropModel', { name: "User" }); 204 | 205 | } catch (error) { 206 | console.error('Error:', error); 207 | } finally { 208 | await client.disconnect(); 209 | } 210 | } 211 | 212 | example(); 213 | ``` 214 | 215 | ## Data Types 216 | 217 | Both Python and Node.js clients define a `Types` object with the following data types: 218 | 219 | - `NUMBER` 220 | - `BOOLEAN` 221 | - `STRING` 222 | - `OBJECT` 223 | - `ARRAY` 224 | 225 | These types are used when defining model structures. 226 | 227 | ## Security Considerations 228 | 229 | - This system does not include authentication or authorization. It is recommended to implement these features for production use. 230 | - Communications are not encrypted by default. Consider using HTTPS/WSS for secure connections. 231 | 232 | ## Limitations 233 | 234 | - The JSON database is not suitable for large volumes of data or complex operations. 235 | - It does not support transactions or complex queries. 236 | 237 | ## Future Improvements 238 | 239 | - Implement authentication and authorization. 240 | - Add support for more complex queries. 241 | - Add support for relationships between models. 242 | 243 | This documentation provides an overview of the project and how to use both the server and clients. For production use, it is recommended to implement additional security measures and consider the mentioned limitations. 244 | -------------------------------------------------------------------------------- /documentation/es/README.md: -------------------------------------------------------------------------------- 1 | # Documentación del Proyecto JsonFlux 2 | 3 | ## Descripción General 4 | 5 | Este proyecto implementa un sistema de base de datos JSON con un servidor y clientes en Python y Node.js. Utiliza Socket.IO para la comunicación en tiempo real entre el servidor y los clientes. 6 | 7 | ## Componentes del Proyecto 8 | 9 | 1. Servidor (Node.js) 10 | 2. Cliente Python 11 | 3. Cliente Node.js 12 | 13 | ## 1. Servidor 14 | 15 | ### Tecnologías Utilizadas 16 | 17 | - Node.js 18 | - Express 19 | - Socket.IO 20 | - json-db-manager (módulo personalizado para manejar la base de datos JSON) 21 | 22 | ### Funcionalidades Principales 23 | 24 | - Manejo de conexiones Socket.IO 25 | - Operaciones CRUD en la base de datos JSON 26 | - Endpoints HTTP para operaciones de base de datos 27 | 28 | ### Operaciones Soportadas 29 | 30 | 1. `addModel`: Añade un nuevo modelo a la base de datos 31 | 2. `create`: Crea un nuevo documento en un modelo específico 32 | 3. `find`: Busca documentos en un modelo u obtiene todos los documentos de un modelo si solo se especifica el nombre 33 | 4. `update`: Actualiza un documento existente 34 | 5. `destroy`: Elimina un documento 35 | 6. `dropModel`: Elimina un modelo completo 36 | 37 | ### Configuración 38 | 39 | El servidor se puede configurar mediante argumentos de línea de comandos: 40 | 41 | ``` 42 | node server.js --port 3030 --logs true --autosave 15000 43 | ``` 44 | 45 | ## 2. Cliente Python 46 | 47 | ### Tecnologías Utilizadas 48 | 49 | - Python 50 | - python-socketio 51 | 52 | ### Clase Principal: `DatabaseClient` 53 | 54 | #### Métodos 55 | 56 | - `connect()`: Conecta al servidor 57 | - `disconnect()`: Desconecta del servidor 58 | - `DB(action, **kwargs)`: Método principal para realizar operaciones en la base de datos 59 | 60 | ### Uso Básico 61 | 62 | ```python 63 | import asyncio 64 | from database_client import execute, Types, connect, disconnect 65 | 66 | 67 | async def main(): 68 | # Conectar 69 | await connect("http://127.0.0.1:3030") 70 | 71 | # Añadir un modelo 72 | model_data = { 73 | "name": { 74 | "type": Types["STRING"], # La key "name" debe ser tipo String 75 | "allowNull": False, # La ley "name" no debe ser nulo al crearse un nuevo usuario 76 | "unique": True, # La key "name" debe ser único para cada usuario, no se puede repetir 77 | }, 78 | "age": { 79 | "type": Types["NUMBER"], 80 | "allowNull": False, 81 | "unique": False, 82 | }, 83 | "isActive": { 84 | "type": Types["BOOLEAN"], 85 | "allowNull": False, 86 | "unique": False, 87 | }, 88 | } 89 | await execute("addModel", name="UserTest", data=model_data) 90 | 91 | # Crear un documento 92 | user_data = {"name": "John Doe", "age": 30, "isActive": True} 93 | await execute("create", name="UserTest", data=user_data) 94 | 95 | # Buscar documentos 96 | result = await execute( 97 | "find", name="UserTest", param="name", equal="John Doe", number=1 98 | ) 99 | 100 | # Actualizar un documento 101 | if result: 102 | print("Se ejecutó") 103 | await execute("update", name="UserTest", last_search=result, data={"age": 31}) 104 | else: 105 | await execute( 106 | "update", 107 | name="UserTest", 108 | search={"param": "name", "value": "John Doe"}, 109 | data={"age": 31}, 110 | ) 111 | 112 | # Eliminar un documento 113 | await execute( 114 | "destroy", name="UserTest", search={"param": "name", "value": "John Doe"} 115 | ) 116 | 117 | # Eliminar un modelo 118 | await execute("dropModel", name="UserTest") 119 | 120 | # Desconectar 121 | await disconnect() 122 | 123 | 124 | asyncio.run(main()) 125 | ``` 126 | 127 | ## 3. Cliente Node.js 128 | 129 | ### Tecnologías Utilizadas 130 | 131 | - Node.js 132 | - socket.io-client 133 | 134 | ### Clase Principal: `DatabaseClient` 135 | 136 | #### Métodos 137 | 138 | - `connect()`: Conecta al servidor 139 | - `disconnect()`: Desconecta del servidor 140 | - `DB(action, params)`: Método principal para realizar operaciones en la base de datos 141 | 142 | ### Uso Básico 143 | 144 | ```javascript 145 | const { DatabaseClient, Types } = require('./database_client'); 146 | 147 | const client = new DatabaseClient('http://127.0.0.1:3030'); 148 | 149 | async function example() { 150 | try { 151 | await client.connect(); 152 | 153 | // Añadir un modelo 154 | const modelData = { 155 | name: { 156 | type: Types.STRING, 157 | allowNull: false, 158 | unique: true 159 | }, 160 | age: { 161 | type: Types.NUMBER, 162 | allowNull: false, 163 | unique: false 164 | }, 165 | isActive: { 166 | type: Types.BOOLEAN, 167 | allowNull: false, 168 | unique: false 169 | } 170 | }; 171 | await client.DB('addModel', { name: "User", data: modelData }); 172 | 173 | // Crear un documento 174 | const userData = { name: "John Doe", age: 30, isActive: true }; 175 | await client.DB('create', { name: "User", data: userData }); 176 | 177 | // Buscar documentos 178 | const result = await client.DB('find', { name: "User", param: "name", equal: "John Doe", number: 1 }); 179 | console.log(result); 180 | 181 | // Actualizar un documento 182 | if (result) { 183 | await client.DB('update', { 184 | name: "User", 185 | last_search: result, 186 | data: { age: 31 } 187 | }); 188 | } else { 189 | await client.DB('update', { 190 | name: "User", 191 | search: { param: "name", value: "John Doe" }, 192 | data: { age: 31 } 193 | }); 194 | } 195 | 196 | // Eliminar un documento 197 | await client.DB('destroy', { 198 | name: "User", 199 | search: { param: "name", value: "John Doe" } 200 | }); 201 | 202 | // Eliminar un modelo 203 | await client.DB('dropModel', { name: "User" }); 204 | 205 | } catch (error) { 206 | console.error('Error:', error); 207 | } finally { 208 | await client.disconnect(); 209 | } 210 | } 211 | 212 | example(); 213 | ``` 214 | 215 | ## Tipos de Datos 216 | 217 | Tanto el cliente Python como el Node.js definen un objeto `Types` con los siguientes tipos de datos: 218 | 219 | - `NUMBER` 220 | - `BOOLEAN` 221 | - `STRING` 222 | - `OBJECT` 223 | - `ARRAY` 224 | 225 | Estos tipos se utilizan al definir la estructura de los modelos. 226 | 227 | ## Consideraciones de Seguridad 228 | 229 | - Este sistema no incluye autenticación ni autorización. Se recomienda implementar estas características para un uso en producción. 230 | - Las comunicaciones no están cifradas por defecto. Considere usar HTTPS/WSS para conexiones seguras. 231 | 232 | ## Limitaciones 233 | 234 | - La base de datos JSON no es adecuada para grandes volúmenes de datos o operaciones complejas. 235 | - No soporta transacciones ni consultas complejas. 236 | 237 | ## Mejoras Futuras 238 | 239 | - Implementar autenticación y autorización. 240 | - Añadir soporte para consultas más complejas. 241 | - Añadir soporte para relaciones entre modelos. 242 | 243 | Esta documentación proporciona una visión general del proyecto y cómo utilizar tanto el servidor como los clientes. Para un uso en producción, se recomienda implementar medidas de seguridad adicionales y considerar las limitaciones mencionadas. 244 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const http = require('http'); 3 | const socketIo = require('socket.io'); 4 | const yargs = require('yargs/yargs'); 5 | const { hideBin } = require('yargs/helpers'); 6 | const jsonDbManager = require("./json-db-manager/json-db-manager.js"); 7 | 8 | //? ---------------------> CONFIGURACIÓN DE ARGUMENTOS <---------------------------- ?// 9 | 10 | const argv = yargs(hideBin(process.argv)) 11 | .option('port', { 12 | alias: 'p', 13 | type: 'number', 14 | description: 'Puerto en el que correrá el servidor', 15 | default: 3030 16 | }) 17 | .option('autosave', { 18 | alias: 'a', 19 | type: 'number', 20 | description: 'Intervalo de autoguardado de la base de datos (en milisegundos)', 21 | default: 15000 22 | }) 23 | .option('logs', { 24 | alias: 'l', 25 | type: 'boolean', 26 | description: 'Habilitar logs de la base de datos', 27 | default: true 28 | }) 29 | .argv; 30 | 31 | //? ---------------------> CONFIGURACIÓN INICIAL <---------------------------- ?// 32 | 33 | const app = express(); 34 | const server = http.createServer(app); 35 | const io = socketIo(server); 36 | 37 | // Inicialización de la base de datos JSON 38 | const db = jsonDbManager(__dirname + "/DB.json", { autosave: argv.autosave, logs: argv.logs }); 39 | 40 | app.use(express.json()); 41 | 42 | //? ---------------------> MANEJO DE SOLICITUDES <---------------------------- ?// 43 | 44 | const handleRequest = (operation, params) => { 45 | const { name, data, param, equal, number, search, value, last_search } = params; 46 | 47 | try { 48 | switch (operation) { 49 | case 'addModel': 50 | db.addModel(name, data.length === 1 ? data[0] : data); 51 | return { message: 'Modelo agregado' }; 52 | 53 | case 'create': 54 | const result = db.create(name, data.length === 1 ? data[0] : data); 55 | return typeof result === 'object' ? result : { message: result }; 56 | 57 | case 'find': 58 | return param && equal 59 | ? db.find(name, { where: (data) => data[param] == equal, limit: Number(number) }) 60 | : db.find(name); 61 | 62 | case 'update': 63 | const target = last_search || (search && db.find(name, { 64 | where: (data) => data[search.param] == search.value, 65 | limit: 1 66 | })); 67 | return target ? db.update(name, target, data.length === 1 ? data[0] : data) : null; 68 | 69 | case 'destroy': 70 | const toDestroy = last_search || (search && value && db.find(name, { 71 | where: (data) => data[search] == value, 72 | limit: 1 73 | })[0]); 74 | return toDestroy ? db.destroy(name, toDestroy) : null; 75 | 76 | case 'dropModel': 77 | db.drop(name); 78 | return { message: `El modelo ${name} ha sido eliminado.` }; 79 | 80 | default: 81 | return { error: 'Operación no válida' }; 82 | } 83 | } catch (error) { 84 | console.error(`Error en operación ${operation}:`, error); 85 | return { error: `Error en operación ${operation}: ${error.message}` }; 86 | } 87 | }; 88 | 89 | //? ---------------------> MANEJO DE CONEXIONES SOCKET <---------------------------- ?// 90 | 91 | const socketHandler = (socket) => { 92 | console.log('¡Administrador conectado!'); 93 | 94 | const operations = ['addModel', 'create', 'find', 'getModel', 'update', 'destroy', 'dropModel']; 95 | 96 | operations.forEach(operation => { 97 | socket.on(operation, (params) => { 98 | try { 99 | const parsedParams = JSON.parse(params); 100 | const result = handleRequest(operation, parsedParams); 101 | socket.emit('response', JSON.stringify(result)); 102 | } catch (error) { 103 | socket.emit('response', JSON.stringify({ error: `Error al procesar la solicitud: ${error.message}` })); 104 | } 105 | }); 106 | }); 107 | 108 | socket.on('disconnect', () => console.log('¡Administrador desconectado!')); 109 | }; 110 | 111 | io.on('connection', socketHandler); 112 | 113 | //? ---------------------> RUTAS HTTP <---------------------------- ?// 114 | 115 | app.get('/', (req, res) => res.status(200).send({ status: 'Active' })); 116 | 117 | const postHandler = (req, res) => { 118 | try { 119 | const params = typeof req.body.params === 'object' ? req.body.params : JSON.parse(req.body.params); 120 | const result = handleRequest(req.path.slice(1), params); 121 | res.json(result); 122 | } catch (error) { 123 | res.status(400).json({ error: `Error al procesar la solicitud: ${error.message}` }); 124 | } 125 | }; 126 | 127 | ['addModel', 'create', 'find', 'update', 'destroy', 'dropModel'].forEach(operation => { 128 | app.post(`/${operation}`, postHandler); 129 | }); 130 | 131 | //? ---------------------> INICIO DEL SERVIDOR <---------------------------- ?// 132 | 133 | server.listen(argv.port, () => { 134 | console.log(`Servidor JsonFlux iniciado en el puerto ${argv.port}`); 135 | console.log(`Autosave configurado a ${argv.autosave} ms`); 136 | console.log(`Logs ${argv.logs ? 'habilitados' : 'deshabilitados'}`); 137 | }); 138 | -------------------------------------------------------------------------------- /json-db-manager/json-db-manager.js: -------------------------------------------------------------------------------- 1 | const jsonDbManager = (path = __dirname + "/DB.json", opts = {}) => { 2 | const fs = require("fs"); 3 | this.path = path; 4 | this.data = { __UNIQUES__: {} }; 5 | this.models = {}; 6 | this.opts = opts; 7 | this.logs = opts.logs !== undefined ? opts.logs : true; 8 | 9 | try { 10 | if (!fs.existsSync(this.path)) { 11 | fs.writeFileSync(this.path, JSON.stringify(this.data), "utf-8"); 12 | } else { 13 | this.data = JSON.parse(fs.readFileSync(this.path, "utf-8")); 14 | } 15 | } catch (err) { 16 | throw new Error("Error al inicializar la base de datos: " + err); 17 | } 18 | 19 | console.log("Conexión a la base de datos exitosa."); 20 | 21 | if (this.opts.autosave) { 22 | if (isNaN(this.opts.autosave)) throw new Error("El autoguardado debe ser un valor de tipo Int"); 23 | setInterval(() => { 24 | this.save(); 25 | }, this.opts.autosave); 26 | } 27 | 28 | this.save = () => { 29 | try { 30 | fs.writeFileSync(this.path, JSON.stringify(this.data), "utf-8"); 31 | } catch (err) { 32 | this.log("Error al guardar datos: " + err); 33 | } 34 | }; 35 | 36 | this.Types = { 37 | NUMBER: "Number", 38 | BOOLEAN: "Boolean", 39 | STRING: "String", 40 | OBJECT: "Object", 41 | ARRAY: "Array" 42 | }; 43 | 44 | // Carga de modelos desde el archivo 45 | try { 46 | const fileContent = JSON.parse(fs.readFileSync(this.path, "utf-8")); 47 | this.data = fileContent; 48 | 49 | this.models = {}; 50 | for (let key in this.data) { 51 | if (key !== "__UNIQUES__") { 52 | this.models[key] = {}; 53 | const firstItem = this.data[key][Object.keys(this.data[key])[0]]; 54 | if (firstItem) { 55 | for (let field in firstItem) { 56 | this.models[key][field] = { 57 | type: firstItem[field] ? firstItem[field].constructor.name : 'String', 58 | allowNull: false 59 | }; 60 | } 61 | } 62 | } 63 | } 64 | console.log("Datos y modelos cargados exitosamente."); 65 | } catch (err) { 66 | console.log("Error al cargar los datos y modelos: " + err); 67 | this.data = { __UNIQUES__: {} }; 68 | this.models = {}; 69 | } 70 | 71 | this.addModel = (modelName, model) => { 72 | if (!this.data[modelName]) this.data[modelName] = {}; 73 | this.models[modelName] = model; 74 | if (!this.data.__UNIQUES__[modelName]) this.data.__UNIQUES__[modelName] = {}; 75 | for (let m in model) { 76 | if (model[m].unique && !this.data.__UNIQUES__[modelName][m]) this.data.__UNIQUES__[modelName][m] = []; 77 | } 78 | }; 79 | 80 | this.find = (model, opts = {}) => { 81 | const time = new Date().getTime(); 82 | let results = []; 83 | if (!this.models[model]) { 84 | this.log(`No se encontró el modelo ${model}`); 85 | return results; 86 | } 87 | 88 | const _limit_1 = opts.limit === 1; 89 | let limit = opts.limit || 10000; 90 | if (opts.where) { 91 | for (let d in this.data[model]) { 92 | if (opts.where(this.data[model][d]) === true) { 93 | results.push(this.data[model][d]); 94 | if (--limit <= 0) break; 95 | } 96 | } 97 | } else { 98 | results = Object.values(this.data[model]); 99 | } 100 | 101 | this.log(`Búsqueda de ${results.length} resultados en ${new Date().getTime() - time}ms`); 102 | return JSON.parse(JSON.stringify(_limit_1 && results.length > 0 ? results[0] : results)); 103 | }; 104 | 105 | this.create = (model, data) => { 106 | const time = new Date().getTime(); 107 | if (!this.models[model]) { 108 | this.log(`El modelo ${model} no existe`); 109 | return null; 110 | } 111 | 112 | let modelData = {}, uniques = {}; 113 | for (let d in this.models[model]) { 114 | if (this.models[model][d].allowNull === false && data[d] === undefined) { 115 | this.log(`El parámetro ${d} no puede ser nulo`); 116 | return null; 117 | } 118 | 119 | if (data[d] === undefined && this.models[model][d].default !== undefined) { 120 | data[d] = this.models[model][d].default; 121 | } 122 | 123 | if (data[d] && data[d].constructor.name !== this.models[model][d].type) { 124 | this.log(`Se requiere un parámetro de tipo ${this.models[model][d].type}, pero se obtuvo ${data[d].constructor.name}`); 125 | return null; 126 | } 127 | 128 | if (this.models[model][d].unique && this.data.__UNIQUES__[model][d].includes(data[d])) { 129 | this.log(`El campo ${d} se encontró duplicado con el valor ${data[d]}`); 130 | return null; 131 | } 132 | 133 | if (this.models[model][d].unique) uniques[d] = data[d]; 134 | modelData[d] = data[d]; 135 | } 136 | 137 | Object.keys(uniques).forEach(u => this.data.__UNIQUES__[model][u].push(uniques[u])); 138 | 139 | const nextIndex = String(Object.keys(this.data[model]).length + 1); 140 | modelData.index = nextIndex; 141 | modelData.createdAt = new Date().getTime(); 142 | this.data[model][nextIndex] = modelData; 143 | 144 | this.log(`Modelo creado en ${new Date().getTime() - time}ms`); 145 | return JSON.parse(JSON.stringify(modelData)); 146 | }; 147 | 148 | this.update = (model, modelToUpdate, data) => { 149 | const time = new Date().getTime(); 150 | if (!this.data[model] || !this.data[model][modelToUpdate.index]) { 151 | this.log(`El modelo o índice no existen`); 152 | return null; 153 | } 154 | 155 | let existingData = JSON.parse(JSON.stringify(this.data[model][modelToUpdate.index])); 156 | 157 | for (let d in data) { 158 | if (!this.models[model][d]) { 159 | this.log(`El parámetro ${d} no pertenece al modelo ${model}`); 160 | return null; 161 | } 162 | 163 | if (data[d] && data[d].constructor.name !== this.models[model][d].type) { 164 | this.log(`Se requiere un parámetro de tipo ${this.models[model][d].type}, pero se obtuvo ${data[d].constructor.name}`); 165 | return null; 166 | } 167 | 168 | if (this.models[model][d].unique) { 169 | const uniqueIndex = this.data.__UNIQUES__[model][d].indexOf(existingData[d]); 170 | if (uniqueIndex !== -1) this.data.__UNIQUES__[model][d].splice(uniqueIndex, 1); 171 | 172 | if (this.data.__UNIQUES__[model][d].includes(data[d])) { 173 | this.log(`El campo ${d} se encontró duplicado con el valor ${data[d]}`); 174 | return null; 175 | } 176 | this.data.__UNIQUES__[model][d].push(data[d]); 177 | } 178 | 179 | existingData[d] = data[d]; 180 | } 181 | 182 | existingData.updatedAt = new Date().getTime(); 183 | this.data[model][modelToUpdate.index] = existingData; 184 | this.log(`Modelo actualizado en ${new Date().getTime() - time}ms`); 185 | return JSON.parse(JSON.stringify(existingData)); 186 | }; 187 | 188 | this.drop = (model) => { 189 | const time = new Date().getTime(); 190 | if (this.data[model]) { 191 | this.data[model] = {}; 192 | this.data.__UNIQUES__[model] = {}; 193 | this.log(`Modelo ${model} eliminado en ${new Date().getTime() - time}ms`); 194 | } else { 195 | this.log(`No se encontró el modelo ${model}`); 196 | } 197 | }; 198 | 199 | this.destroy = (model, modelData) => { 200 | const time = new Date().getTime(); 201 | if (this.data[model] && modelData.index && this.data[model][modelData.index]) { 202 | Object.keys(this.data.__UNIQUES__[model]).forEach(un => { 203 | const uniqueIndex = this.data.__UNIQUES__[model][un].indexOf(this.data[model][modelData.index][un]); 204 | if (uniqueIndex !== -1) this.data.__UNIQUES__[model][un].splice(uniqueIndex, 1); 205 | }); 206 | delete this.data[model][modelData.index]; 207 | this.log(`Índice ${modelData.index} del modelo ${model} eliminado en ${new Date().getTime() - time}ms`); 208 | } else { 209 | this.log(`El modelo o índice no existen`); 210 | } 211 | }; 212 | 213 | this.log = (message) => this.logs && console.log("[jsonDbManager] " + message); 214 | return this; 215 | }; 216 | 217 | module.exports = jsonDbManager; 218 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jsonflux", 3 | "version": "1.0.0", 4 | "description": "A database on your own server in real time that allows you to save all the data of your apps in one place in a very efficient and private way, without limits or third-party problems", 5 | "main": "index.js", 6 | "scripts": { 7 | "start": "node index.js" 8 | }, 9 | "keywords": ["database", "json", "socket-io", "python3", "nodejs-server"], 10 | "author": "DevFast Project", 11 | "license": "Apache2.0", 12 | "dependencies": { 13 | "express": "^4.18.2", 14 | "socket.io": "^4.7.4", 15 | "yargs": "^17.7.2" 16 | } 17 | } 18 | --------------------------------------------------------------------------------