### Nicola Core - HTTP Server Setup and Routing Source: https://context7.com/ericktiznado/nicola/llms.txt Demonstrates setting up the Nicola HTTP server, defining basic GET and POST routes, handling URL parameters, processing JSON request bodies, and managing file uploads. It also shows how to start the server with optional timeout configurations. ```javascript import Nicola from "nicola-framework"; const app = new Nicola(); // Basic route with JSON response app.get("/", (req, res) => { res.json({ message: "Hello from Nicola!", status: "ok" }); }); // Route with URL parameters app.get("/users/:id", (req, res) => { const userId = req.params.id; res.json({ userId, found: true }); }); // POST with automatic JSON body parsing app.post("/users", (req, res) => { const { name, email } = req.body; res.statusCode = 201; res.json({ created: true, user: { name, email } }); }); // File upload with multipart/form-data app.post("/upload", (req, res) => { if (!req.files || !req.files.avatar) { res.statusCode = 400; return res.end("No file uploaded"); } const file = req.files.avatar; res.json({ filename: file.filename, type: file.type, size: file.size }); }); // Start server with optional timeouts via environment variables // NICOLA_REQUEST_TIMEOUT, NICOLA_HEADERS_TIMEOUT, NICOLA_KEEP_ALIVE_TIMEOUT app.listen(3000, () => { console.log("Server running on http://localhost:3000"); }); ``` -------------------------------- ### Complete Nicola Framework Application Example (JavaScript) Source: https://context7.com/ericktiznado/nicola/llms.txt This JavaScript code demonstrates a complete application using the Nicola Framework. It includes setting up the server, defining a database model (User), implementing authentication middleware, creating API routes for registration, login, and profile retrieval, and starting the server. It utilizes various components of the framework like Remote, Regulator, Coherer, Dynamo, and Insulator. ```javascript import Nicola, { Remote, Regulator, Coherer, Dynamo, Insulator, EasyCors } from "nicola-framework"; // Load environment variables Regulator.load(); const app = new Nicola(); // Define User model class User extends Dynamo.Model { static tableName = "users"; static schema = { email: { type: "string", required: true }, password: { type: "string", required: true } }; } // Auth middleware const authenticate = (req, res, next) => { const token = req.headers.authorization?.split(" ")[1]; if (!token) { res.statusCode = 401; return res.json({ error: "No token provided" }); } try { req.user = Coherer.verify(token); next(); } catch (err) { res.statusCode = 401; res.json({ error: err.message }); } }; // API Router const api = new Remote(); // Public: Register api.post("/register", Insulator({ email: "string", password: "string" }), async (req, res) => { try { const user = await User.create(req.body); res.statusCode = 201; res.json({ id: user.id, email: user.email }); } catch (err) { res.statusCode = 500; res.json({ error: "Registration failed" }); } }); // Public: Login api.post("/login", async (req, res) => { const { email, password } = req.body; const users = await User.where("email", email).where("password", password).get(); if (users.length === 0) { res.statusCode = 401; return res.json({ error: "Invalid credentials" }); } const token = Coherer.sign({ userId: users[0].id }, { expiresIn: "7d" }); res.json({ token }); }); // Protected: Get profile api.get("/profile", authenticate, async (req, res) => { const users = await User.where("id", req.user.userId).get(); if (users.length === 0) { res.statusCode = 404; return res.json({ error: "User not found" }); } res.json({ email: users[0].email }); }); // Mount API router app.use("/api", api); // Health check app.get("/health", (req, res) => { res.json({ status: "ok", timestamp: Date.now() }); }); // Start server const start = async () => { await Dynamo.connect(); app.listen(3000, () => { console.log("Server running on http://localhost:3000"); }); }; start().catch(console.error); ``` -------------------------------- ### Nicola CLI Commands for Project Management Source: https://context7.com/ericktiznado/nicola/llms.txt The Nicola CLI provides commands for scaffolding new projects and managing the development server. Key commands include `init` for creating a new project with a starter template and `start` for launching the development server with hot-reloading capabilities. The generated project structure includes an entry point (`app.js`), configuration files, and example directories for controllers and routes. ```bash # Create new project with starter template npx nicola init my-api cd my-api npm install # Start development server with hot reload npm start # or npx nicola start # Generated project structure: # my-api/ # app.js # Entry point # package.json # With "type": "module" # src/ # controllers/ # user.controller.js # Example controller # routes/ # user.Routes.js # Example routes # Generated app.js example: # import Nicola, { Regulator } from "nicola-framework"; # import UserRoute from "./src/routes/user.Routes.js"; # # Regulator.load(); # const app = new Nicola(); # app.use("/user", UserRoute); # app.get("/", (req, res) => res.json({ message: "Welcome" })); # app.listen(3000); ``` -------------------------------- ### Nicola JWT Authentication with Coherer Source: https://context7.com/ericktiznado/nicola/llms.txt Shows how to implement JWT authentication using Nicola's `Coherer` module. It includes an example of a login endpoint to generate tokens and a protected route that uses an authentication middleware to verify tokens and attach user information to the request. ```javascript import Nicola, { Regulator, Coherer } from "nicola-framework"; // Load environment variables (requires .env with NICOLA_SECRET) Regulator.load(); const app = new Nicola(); // Login endpoint - generate JWT token app.post("/login", (req, res) => { const { username, password } = req.body; // Validate credentials (example) if (username !== "admin" || password !== "secret") { res.statusCode = 401; return res.json({ error: "Invalid credentials" }); } // Sign token with expiration (supported: s, m, h, d, y) const token = Coherer.sign( { userId: 1, username, role: "admin" }, { expiresIn: "24h" } ); res.json({ token }); }); // Authentication middleware const authMiddleware = (req, res, next) => { const authHeader = req.headers.authorization || ""; const [scheme, token] = authHeader.split(" "); if (scheme !== "Bearer" || !token) { res.statusCode = 401; return res.json({ error: "Missing token" }); } try { const payload = Coherer.verify(token); req.user = payload; next(); } catch (err) { res.statusCode = 401; // err.message: "Token Invalido" | "Token Expired" res.json({ error: err.message }); } }; // Protected route app.get("/profile", authMiddleware, (req, res) => { res.json({ user: req.user }); }); app.listen(3000); ``` -------------------------------- ### Nicola Core - HTTP Server API Source: https://context7.com/ericktiznado/nicola/llms.txt The main entry point for creating web applications. Extends the router with HTTP server capabilities, automatic body parsing, and response helpers. ```APIDOC ## Nicola Core - HTTP Server ### Description The main entry point for creating web applications. Extends the router with HTTP server capabilities, automatic body parsing, and response helpers. ### Method GET, POST ### Endpoint /, /users/:id, /users, /upload ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user. #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email of the user. - **avatar** (file) - Required - The avatar file to upload. ### Request Example ```json { "name": "John Doe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (200) - **message** (string) - A greeting message. - **status** (string) - The status of the response. - **userId** (string) - The ID of the user. - **found** (boolean) - Indicates if the user was found. - **created** (boolean) - Indicates if the user was created. - **user** (object) - The created user object. - **filename** (string) - The name of the uploaded file. - **type** (string) - The type of the uploaded file. - **size** (number) - The size of the uploaded file. #### Response Example ```json { "message": "Hello from Nicola!", "status": "ok" } ``` ```json { "userId": "123", "found": true } ``` ```json { "created": true, "user": { "name": "John Doe", "email": "john.doe@example.com" } } ``` ```json { "filename": "avatar.jpg", "type": "image/jpeg", "size": 10240 } ``` ``` -------------------------------- ### Load Environment Variables with Regulator Source: https://context7.com/ericktiznado/nicola/llms.txt Loads environment variables from a .env file in the current working directory using the Regulator module. It supports the KEY=value format, comments, and empty lines. Ensure this is called before accessing environment-dependent features. ```javascript import { Regulator } from "nicola-framework"; // Load .env file before using environment-dependent features Regulator.load(); // Environment variables are now available console.log(process.env.NICOLA_SECRET); console.log(process.env.DB_HOST); console.log(process.env.NODE_ENV); ``` -------------------------------- ### Nicola Router - Standalone Route Grouping Source: https://context7.com/ericktiznado/nicola/llms.txt Illustrates using the `Remote` class to create standalone routers for modular route organization. It shows how to define routes within sub-routers and mount them onto the main application with path prefixes, enabling nested routing structures. ```javascript import Nicola, { Remote } from "nicola-framework"; const app = new Nicola(); // Create a sub-router for API routes const apiRouter = new Remote(); apiRouter.get("/ping", (req, res) => { res.end("pong"); }); apiRouter.get("/status", (req, res) => { res.json({ status: "healthy", uptime: process.uptime() }); }); apiRouter.post("/echo", (req, res) => { res.json({ received: req.body }); }); // Create another sub-router for admin routes const adminRouter = new Remote(); adminRouter.get("/dashboard", (req, res) => { res.json({ admin: true, section: "dashboard" }); }); // Mount routers with path prefixes app.use("/api", apiRouter); // /api/ping, /api/status, /api/echo app.use("/admin", adminRouter); // /admin/dashboard // Middleware applies to all routes below app.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); }); app.listen(3000); ``` -------------------------------- ### LiveCurrent Hot Reload Development Server for Nicola Source: https://context7.com/ericktiznado/nicola/llms.txt LiveCurrent is a development tool that provides a hot-reloading development server for Nicola applications. It watches specified entry point files and automatically restarts the Node.js process upon detecting changes in supported file types (.js, .json, .env). It includes features like debouncing, interactive shortcuts, and smart crash analysis. ```javascript import LiveCurrent from "nicola-framework/dev-tools/LiveCurrent"; // Create watcher for entry point const watcher = new LiveCurrent("app.js"); // Start watching and auto-reloading watcher.boot(); // Features: // - Watches .js, .json, .env files // - Ignores node_modules, .git, logs, coverage, test directories // - Debounces rapid changes (200ms delay) // - Interactive shortcuts: r=reload, c=clear, i=inspect, q=quit, h=help // - Smart crash analysis with code frame display // Typically used via CLI: // npx nicola start ``` -------------------------------- ### Configure CORS with EasyCors Middleware Source: https://context7.com/ericktiznado/nicola/llms.txt Provides Cross-Origin Resource Sharing middleware for the Nicola framework. It supports wildcard or whitelist origins and automatically handles OPTIONS preflight requests. CORS headers like `Access-Control-Allow-Origin` are set based on the configuration. ```javascript import Nicola, { EasyCors } from "nicola-framework"; const app = new Nicola(); // Allow all origins (default) app.use(EasyCors()); // Or whitelist specific origins app.use(EasyCors({ origin: ["https://myapp.com", "http://localhost:3000"] })); // CORS headers set: // Access-Control-Allow-Origin: * or specific origin // Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, PATCH // Access-Control-Allow-Headers: Content-Type, Authorization // OPTIONS requests automatically return 204 No Content app.get("/api/data", (req, res) => { res.json({ data: "accessible cross-origin" }); }); app.listen(3000); ``` -------------------------------- ### Add Security Headers with Teleforce Source: https://context7.com/ericktiznado/nicola/llms.txt A middleware for the Nicola framework that automatically adds basic security headers to all outgoing responses. It helps mitigate common web vulnerabilities by setting headers like `X-Content-Type-Options`, `X-Frame-Options`, and `X-XSS-Protection`. ```javascript import Nicola from "nicola-framework"; import Teleforce from "nicola-framework/middlewares/Teleforce"; const app = new Nicola(); // Add security headers to all responses app.use(Teleforce); // Headers added: // X-Content-Type-Options: nosniff // X-Frame-Options: Deny // X-XSS-Protection: 1 // X-Powered-By: (removed) app.get("/", (req, res) => { res.json({ secure: true }); }); app.listen(3000); ``` -------------------------------- ### PatternBuilder Fluent Regex API for JavaScript Source: https://context7.com/ericktiznado/nicola/llms.txt PatternBuilder offers a fluent API for constructing regular expressions in a readable, chainable syntax. It supports various methods for defining patterns, matching strings, extracting content, and replacing text. The `toRegex()` method compiles the pattern into a standard JavaScript RegExp object. ```javascript import { PatternBuilder } from "nicola-framework"; // Validate email format const emailPattern = new PatternBuilder() .startOfLine() .word().oneOrMore() .find("@") .word().oneOrMore() .find(".") .word().oneOrMore() .endOfLine(); console.log(emailPattern.matches("user@example.com")); // true console.log(emailPattern.matches("invalid-email")); // false // Validate phone number (555-123-4567) const phonePattern = new PatternBuilder() .startOfLine() .digit().exactly(3) .find("-") .digit().exactly(3) .find("-") .digit().exactly(4) .endOfLine(); console.log(phonePattern.matches("555-123-4567")); // true // Extract text between delimiters using cut() const quotePattern = new PatternBuilder().cut('"'); const result = quotePattern.get('name="Nicola Framework"'); console.log(result[1]); // "Nicola Framework" // Extract content between different delimiters const tagPattern = new PatternBuilder().cut('<', '>'); const tagResult = tagPattern.get('Hello World'); console.log(tagResult[1]); // "title" // Pattern with optional parts const urlPattern = new PatternBuilder() .find("http") .find("s").maybe() .find("://") .word().oneOrMore(); console.log(urlPattern.matches("https://example")); // true console.log(urlPattern.matches("http://example")); // true // Get compiled regex const regex = emailPattern.toRegex(); console.log(regex); // /^\w+@\w+\.\w+$/ // Replace matches const censorPattern = new PatternBuilder().digit().oneOrMore(); const censored = censorPattern.global().replace("Call 555-1234", "XXX"); console.log(censored); // "Call XXX-XXX" ``` -------------------------------- ### PostgreSQL ORM Operations with Dynamo Source: https://context7.com/ericktiznado/nicola/llms.txt Provides a simple ORM layer for PostgreSQL interactions using the Dynamo module. It requires the 'pg' package and database environment variables loaded via Regulator. Supports model definition, connection, CRUD operations, querying, updating, and deleting records. ```javascript import { Regulator, Dynamo } from "nicola-framework"; Regulator.load(); // Define a model class User extends Dynamo.Model { static tableName = "users"; static schema = { name: { type: "string", required: true }, email: { type: "string", required: true }, age: { type: "number", required: false } }; } // Connect and perform operations await Dynamo.connect(); // Insert with schema validation const newUser = await User.create({ name: "Alice", email: "alice@example.com", age: 28 }); console.log(newUser); // { id: 1, name: "Alice", email: "alice@example.com", age: 28 } // Select all records const allUsers = await User.all(); // Query with conditions const adults = await User.where("age", ">=", 18).get(); // Select specific columns const names = await User.select("name, email").get(); // Chained query with ordering and pagination const latestUsers = await User.query() .select(["id", "name", "email"]) .where("active", true) .orderBy("created_at", "DESC") .limit(10) .offset(0) .get(); // Update with condition (returns affected row count) const updated = await User.where("id", 1).update({ name: "Alice Smith" }); // Delete with condition (returns affected row count) const deleted = await User.where("id", 1).delete(); // Disconnect when done await Dynamo.disconnect(); ``` -------------------------------- ### Remote - Router Module API Source: https://context7.com/ericktiznado/nicola/llms.txt Standalone router for creating modular route groups. Can be nested within the main app or other routers using the `use()` method. ```APIDOC ## Remote - Router Module ### Description Standalone router for creating modular route groups. Can be nested within the main app or other routers using the `use()` method. ### Method GET, POST ### Endpoint /api/ping, /api/status, /api/echo, /admin/dashboard ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **field1** (any) - The data to be echoed back. ### Request Example ```json { "message": "Hello, world!" } ``` ### Response #### Success Response (200) - **pong** (string) - A response indicating the server is alive. - **status** (string) - The status of the server. - **uptime** (number) - The uptime of the server in seconds. - **received** (object) - The data received in the request body. - **admin** (boolean) - Indicates if the user has admin privileges. - **section** (string) - The section of the admin dashboard. #### Response Example ```json "pong" ``` ```json { "status": "healthy", "uptime": 12345.67 } ``` ```json { "received": { "message": "Hello, world!" } } ``` ```json { "admin": true, "section": "dashboard" } ``` ``` -------------------------------- ### Shadowgraph Request Logger Middleware for Nicola Source: https://context7.com/ericktiznado/nicola/llms.txt The Shadowgraph middleware logs incoming request details after the response has been sent. It requires the 'nicola-framework' package. The logs include the HTTP method, path, status code, status message, and duration in milliseconds. ```javascript import Nicola from "nicola-framework"; import Shadowgraph from "nicola-framework/middlewares/Shadowgraph"; const app = new Nicola(); // Enable request logging app.use(Shadowgraph); // Logs format: [METHOD] /path - STATUS STATUS_MESSAGE - DURATIONms // Example: [GET] /api/users - 200 OK - 15ms app.get("/api/users", (req, res) => { res.json([{ id: 1, name: "Alice" }]); }); app.listen(3000); ``` -------------------------------- ### BlackBox Error Handler Middleware for Nicola Source: https://context7.com/ericktiznado/nicola/llms.txt The BlackBox middleware provides automatic error handling for thrown errors within a Nicola application. It displays HTML error pages, with stack traces hidden in production environments. It handles both synchronous and asynchronous errors, and allows manual error propagation using `next()`. ```javascript import Nicola from "nicola-framework"; const app = new Nicola(); // Errors are automatically caught and displayed app.get("/error", (req, res) => { throw new Error("Something went wrong!"); }); // Async errors are also caught app.get("/async-error", async (req, res) => { await Promise.reject(new Error("Async failure")); }); // Manual error propagation via next() app.get("/manual-error", (req, res, next) => { const err = new Error("Manual error"); next(err); }); // In development: Shows error message and stack trace // In production: Shows "Internal Server Error" only app.listen(3000); ``` -------------------------------- ### Validate Request Body with Insulator Source: https://context7.com/ericktiznado/nicola/llms.txt Acts as middleware for validating request body fields by presence and type using JavaScript's `typeof`. It integrates with the Nicola framework to apply validation schemas to incoming requests. Validation errors result in a 400 Bad Request response with descriptive messages. ```javascript import Nicola, { Insulator } from "nicola-framework"; const app = new Nicola(); // Define validation schema const createUserSchema = { name: "string", email: "string", age: "number" }; const updateUserSchema = { name: "string" }; // Apply validation middleware before handler app.post("/users", Insulator(createUserSchema), (req, res) => { // req.body is guaranteed to have name (string), email (string), age (number) const { name, email, age } = req.body; res.statusCode = 201; res.json({ created: true, user: { name, email, age } }); }); app.patch("/users/:id", Insulator(updateUserSchema), (req, res) => { const { name } = req.body; res.json({ updated: true, name }); }); // Validation errors return 400 with messages: // - Missing field: "Falta campo: email" // - Wrong type: "El campo age debe ser number" app.listen(3000); ``` -------------------------------- ### Coherer - JWT Authentication API Source: https://context7.com/ericktiznado/nicola/llms.txt Built-in JWT implementation using HS256 algorithm with HMAC-SHA256 signing. Requires `NICOLA_SECRET` environment variable. ```APIDOC ## Coherer - JWT Authentication ### Description Built-in JWT implementation using HS256 algorithm with HMAC-SHA256 signing. Requires `NICOLA_SECRET` environment variable. ### Method POST, GET ### Endpoint /login, /profile ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **username** (string) - Required - The username for login. - **password** (string) - Required - The password for login. ### Request Example ```json { "username": "admin", "password": "secret" } ``` ### Response #### Success Response (200) - **token** (string) - The JWT token generated upon successful login. - **user** (object) - The user object containing payload information. #### Error Response (401) - **error** (string) - An error message indicating invalid credentials, missing token, or invalid token. #### Response Example ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } ``` ```json { "user": { "userId": 1, "username": "admin", "role": "admin", "iat": 1678886400, "exp": 1678972800 } } ``` ```json { "error": "Invalid credentials" } ``` ```json { "error": "Missing token" } ``` ```json { "error": "Token Expired" } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.