{"id":26590106,"url":"https://github.com/tomkoooo/tbase","last_synced_at":"2026-04-10T15:53:53.575Z","repository":{"id":282274142,"uuid":"948046265","full_name":"Tomkoooo/tbase","owner":"Tomkoooo","description":"The ultimate BaaS in a single npm package.","archived":false,"fork":false,"pushed_at":"2025-03-13T17:02:38.000Z","size":43,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-13T18:26:39.252Z","etag":null,"topics":["baas","backend","nextjs","npm","ts"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/@tomkoooo/tbase","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Tomkoooo.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-03-13T16:54:23.000Z","updated_at":"2025-03-13T17:02:41.000Z","dependencies_parsed_at":"2025-03-13T18:36:44.613Z","dependency_job_id":null,"html_url":"https://github.com/Tomkoooo/tbase","commit_stats":null,"previous_names":["tomkoooo/tbase"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Tomkoooo%2Ftbase","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Tomkoooo%2Ftbase/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Tomkoooo%2Ftbase/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Tomkoooo%2Ftbase/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Tomkoooo","download_url":"https://codeload.github.com/Tomkoooo/tbase/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245105470,"owners_count":20561527,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["baas","backend","nextjs","npm","ts"],"created_at":"2025-03-23T13:20:49.232Z","updated_at":"2025-12-30T23:32:12.642Z","avatar_url":"https://github.com/Tomkoooo.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Tbase - Simple Socket-Based Backend Library\n\n![npm](https://img.shields.io/npm/v/@tomkoooo/tbase) ![License](https://img.shields.io/npm/l/@tomkoooo/tbase)\n\n**Tbase** is a lightweight, socket-based backend solution packed into a single npm library. With just one `Client` class and a prebuilt server, you can set up a fully functional backend in as little as 10 lines of code. No need for complex API routes or server modifications—Tbase handles it all out of the box.\n\n**Demo at: [Github](https://github.com/Tomkoooo/tbase-demo)**\n\n## Key Features\n- **Real-Time Sockets**: Built-in WebSocket support for effortless real-time communication.\n- **Database Support**: Seamless integration with MongoDB (NoSQL) and MySQL (SQL).\n- **Authentication**: JWT-based sign-up/sign-in with session management.\n- **Database Actions**: Prebuilt CRUD operations (`get`, `add`, `update`, `delete`) with real-time updates.\n- **User Management**: Permissions, teams, and online user tracking.\n- **File Storage**: Bucket-based file API for uploads and management.\n- **Push Notifications**: Cross-platform notifications with VAPID and APNs support.\n- **SSR \u0026 CSR**: Works on both server-side rendering (SSR) and client-side rendering (CSR).\n- **Frontend Freedom**: Control everything from the frontend—no backend setup required.\n- **Permission and Preferences**: On account and users-scope.\n\n- **Mailer**: Send mails and handle user verifications on the frontend. (in development.)\n\n---\n\n## Getting Started\n\n### Installation\nInstall Tbase via npm: (still in development)\n```bash\nnpm install @tomkoooo/tbase\n```\n### Basic Setup\nTbase provides a Client class as the main entry point. Initialize it with optional WebSocket server URI (defaults to localhost:3000 if not specified).\n\n```javascript\n\nconst { Client } = require('tbase');\n\n// Basic client setup\nconst client = new Client(); // Uses default server at localhost:3000\n```\n\n**YOU NEED THIS SERVER.JS FOR THE WEBSOCKET CONNECTION**\n[get the server.js file (nextjs)](https://github.com/Tomkoooo/tbase-demo/blob/main/server.js)\nChange the imports for the npm package.\n\n#### Database Connection\nConnect to MongoDB or MySQL with a simple configuration:\n\n- MongoDB:\n```javascript\n\nexport const mongoClient = new Client()\n  .database('mongodb')\n  .connection({\n    url: 'mongodb://localhost:27017',\n    dbName: 'socket-test',\n  });\n  ```\n- MySQL:\n```javascript\nexport const mysqlClient = new Client()\n  .database('mysql')\n  .connection({\n    host: 'localhost',\n    user: 'root',\n    port: 3306,\n    database: 'socket-test',\n  });\n  ```\n\nOnce connected, you're linked to both the socket server and your database!\n\n## Core Features\n### 1. Socket Communication\nReal-time communication is at the heart of Tbase. Use these methods to interact with sockets:\n\n **Subscribe/Listen: Listen to events on a specific channel.**\n```javascript\n\nclient.subscribe('chat', (message) =\u003e {\n  console.log('Chat message:', message);\n});\n```\n**Unsubscribe: Stop listening to a channel.**\n```javascript\n\nclient.unsubscribe('chat');\n```\n **Send: Emit data to a channel.**\n\n```javascript\n\nclient.send('chat', 'Hello, world!');\n```\n **Example (React):**\n\n```javascript\n\nuseEffect(() =\u003e {\n  client.subscribe('chat', (message) =\u003e {\n    setMessages((prev) =\u003e [...prev, message.message]);\n  });\n  return () =\u003e client.unsubscribe('chat');\n}, []);\n```\n***\n### 2. Database Operations\nPerform CRUD operations with real-time updates using the ActionBuilder:\n\n **Get Data:**\n```javascript\n\nmongoClient\n  .get('users')\n  .query(\"collection('users').find().toArray()\")\n  .setState(setUsers) // Optional: Update state based on the CRUD method\n  .callback((response) =\u003e console.log('Response:', response))\n  .execute();\n  ```\nOther Actions: Use add, update, or delete similarly.\n **Raw Query:**\n```javascript\n\nmysqlClient.execute('users', 'SELECT * FROM users', (data) =\u003e console.log(data));\n```\n***\n### 3. Authentication (client.account())\nManage user authentication with ease:\n\n **Sign Up/Sign In:**\n```javascript\n\ndatabaseClient.signUp('user@example.com', 'password', (data) =\u003e console.log(data));\ndatabaseClient.signIn('user@example.com', 'password', (data) =\u003e console.log(data));\ndatabaseClient.validate('jwt_string' (data) =\u003e console.log(data)); //gives back the user by provided jwt\n```\nReturns a JWT (stored in localStorage) and session ID (stored in cookies) under t_auth.\n\n **Get User:**\n```javascript\n\ndatabaseClient.account().get((user) =\u003e console.log(user));\n```\nReturns a user object if there is a valid JWT token stored\n\n**Session Management: Use getSession, killSession, setSession, etc**\n- **public getSessions: (callback: (data: any) =\u003e void)**\n    - Gives back all the user's sessions if there is a valid JWT registered \n    - Note: on server-side use the database class and on that the getSessions method with the userId as a parameter\n- **public setSession: (sessionData: string, callback: (data: any) =\u003e void)**\n    - Register a new session with the sessionData string if there is a valid JWT\n    - Note: on server-side use the database class and on that the setSession method with the userId and the new sessionId string as a parameter\n- **public killSession: (callback: (data: any) =\u003e void)**\n    - Kills the user current session from the database and removes the tokens from localStorage and cookies \n    - Note: on server-side use the database class and on that the kilSession method with the sessionId as a parameter\n- **public killSessions: (callback: (data: any) =\u003e void)**\n    - Kills the user's all session from the database and removes the tokens from localStorage and cookies \n    - Note: on server-side use the database class and on that the kilSessions method with the userId as a parameter\n- **public changeSession: (newSessionString: sring, callback: (data: any) =\u003e void)**\n    - Changes the user's current session if there is a valid JWT\n    Note: It not updates the cookies\n    - Note: on server-side use the database class and on that the changeSession method with the changable sessionId and the new sessionId as a parameter\n***\n### 4. User Management (client.users())\n***Requires an active JWT session:***\n**List Users:**\n```javascript\n\ndatabaseClient.users().listAll((users) =\u003e console.log(users));\ndatabaseClient.users().getUser('userId2', (users) =\u003e console.log(users)); // gives back specific user obj\ndatabaseClient.users().getUsers(['userid1', 'userid2'], (users) =\u003e console.log(users)); // gives back users obj in an array by their userId from a list\ndatabaseClient.users().listOnline((onlineUsers) =\u003e console.log(onlineUsers));\n//Note a user can be online if after socket connection there is a getAccount or getSession call (client-sde authentication)\n```\n**Real-Time Online Users:**\n```javascript\nclient.users().listenOnlineUsers((users) =\u003e console.log(users));\n```\n***\n### 5. File Storage (Bucket API)\nStore and manage files in buckets:\n***JWT session needed***\n\n**Create Bucket:**\n```javascript\n\nconst bucketId = await databaseClient.createBucket();\n```\n**Upload File:**\n```javascript\n\nawait databaseClient.uploadFile(bucketId, { name: 'file.txt', type: 'text/plain', data: buffer });\n ```\n**List Files:**\n```javascript\n\nconst files = await databaseClient.listFiles(bucketId);\n```\n**Other calls:**\n```javascript\nawait databaseClient.deleteFile(bucketId, fileId); //deletes a file in the bucket\nconst buckets = await databaseClient.listBuckets(); //list of all existing buckets in the db\nawait databaseClient.deleteBucket(bucketId); //deletes the corresponfing bucket table\nawait databaseClient.renameBucker(bucketId, newBucketString); //renames the bucket Note: new name = bucket_{newNameString}\n```\n***\n### 6. Push Notifications\nEnable notifications with VAPID keys (and optional APNs for Apple):\n\n**Subscribe/unsubscribe:**\n\n```javascript\nclient.subscribeToNotification('user123');\nclient.unsubscribeFromNotification('user123');\n```\n**Send Notification:**\n```javascript\n\nclient.sendNotification('user123', { title: 'Hello', message: 'New update!' }); //sends notification with the corresponding user based on userId\n```\n***\n### 7. Server-Side Rendering (SSR)\nUse the Database class for server-side operations:\n\n```javascript\n\nconst { Database, MongoDB } = require('tbase');\n\nconst db = new Database(new MongoDB({\n  url: 'mongodb://localhost:27017',\n  dbName: 'socket-test',\n}));\n\n// Get user session\nexport const getSession = async (sessionId) =\u003e {\n  return await db.getSession(sessionId);\n};\n```\n#### **avaible methods under database: db.{method name}**\n\n***account***\n- async signUp(payload: {email: string, password: string})\n- async signIn(email, password)\n- async getAccount(userId)\n- async getSession(sessionId)\n- async getSessions(userId)\n- async setSession(userId, sessionId)\n- async killSession(sessionId)\n- async killSessions(userId)\n- async changeSession(sessionId, newSessionId)  \n\n***users***\n- async getUser(userId)\n- async getUsers(userIds)\n- async listUsers()\n\n***Notification***\n- async storeSubscription(userId, subscription) \n  - subscription obj generated by the notification class\n- async upsert(table, data) \n  - updates/inserts the subscription from the notification class\n- async delete(table, query) \n  - deletes a subscription from the notification class\n- async find(table, query)\n  - finds a table and gives back every data that are in it \n  - used to retreive subscriptions in the notification clasy\n\n***Bucket***\n- async createBucket()\n- async uploadFile(bucketId, file)\n- async getFile(bucketId, fileId)\n- async listFiles(bucketId)\n- async deleteFile(bucketId, fileId)\n- async listBuckets()\n- async deleteBucket(bucketId)\n- async renameBucket(oldBucketId, newBucketId)\n\n***Permissions***\n- item permissions\n  - async createPermission(itemId, requireAction, requireRole = null)\n  - async getPermission(permissionId)\n  - async getPermissions(itemId = null)\n  - async updatePermission(permissionId, itemId, requireAction, requireRole = null)\n  - async deletePermission(permissionId)\n- user permissions\n\n***\n### 8.Configuration\n**Connection Info**\n```typescript\n\ninterface ConnectionInfo {\n  url?: string;        // MongoDB URL\n  dbName?: string;     // Database name\n  host?: string;       // MySQL host\n  user?: string;       // MySQL user\n  password?: string;   // MySQL password\n  database?: string;   // MySQL database\n  port?: number;       // MySQL port\n}\n```\n**Environment Variables (Notifications)**\n```bash\n\nNEXT_PUBLIC_VAPID_PUBLIC=your_public_key\nNEXT_PUBLIC_VAPID_PRIVATE=your_private_key\nNEXT_PUBLIC_VAPID_MAIL=your_email@example.com\nNEXT_PUBLIC_APNS_TEAM_ID=your_team_id\nNEXT_PUBLIC_APNS_KEY_ID=your_key_id\nNEXT_PUBLIC_APNS_KEY_FILE=path/to/key.pem\nNEXT_PUBLIC_APNS_BUNDLE_ID=your_bundle_id\n```\n***\n## Why Tbase?\n***Simplicity:*** One class, one library, endless possibilities.\n***Flexibility:*** Works with any frontend framework or SSR setup.\n***Scalability:*** Real-time features and database support out of the box.\n\n## Start building your next app with Tbase today!\n\nLicense\nMIT © Tomkoooo/sironic","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftomkoooo%2Ftbase","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftomkoooo%2Ftbase","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftomkoooo%2Ftbase/lists"}