Application Setup
With your environment, database, and models ready — it's time to spin up the application using the App
class from Noblex.
This will initialize your server, load routes, apply middleware, and handle global responses and errors.
code src/app.ts
import * as env from "./env.js";
import { App, parser } from "noblex";
import type { Request, Response, NextFunction } from "noblex";
import "./modules/wallets/wallets.controller.js";
import Wallet from "./modules/wallets/wallets.module.js";
new App({
host: env.APP_HOST,
port: env.APP_PORT,
set: [["query parser", "extended"]],
middlewares: {
static: [parser.urlencoded({ extended: true }), parser.json()],
dynamic: [
(req: Request, res: Response, next: NextFunction) => {
console.log("dynamic middleware test");
next();
},
],
},
handlers: {
response: (req: Request, res: Response, next: NextFunction) => {
res.status(200).json(res.locals.data);
},
notFound: (req: Request, res: Response, next: NextFunction) => {
res.status(404).json({ error: "Not Found" });
},
error: (err: any, req: Request, res: Response, next: NextFunction) => {
console.error(err);
res.status(500).json({ error: "Internal Server Error" });
},
},
crud: {
models: [[Wallet, "wallets"]],
routes: [
{
method: "get",
path: "/test",
middleware: [],
ignore: [],
response: async function (req: Request) {
const users = await this.method.find();
const blogs = await this.method.model.find();
return { users, blogs };
},
},
],
},
});
What This Does
-
Imports environment and core dependencies
Loads your.env
config, your controller, and model definitions. -
Initializes the Noblex app
Boots your API server with all configuration in place.
Config Breakdown
host
and port
Sets the server host and port from your .env
file.
host: env.APP_HOST,
port: env.APP_PORT,
set
Applies Express
app.set()
options. For example, enabling extended query parsing:
set: [["query parser", "extended"]],
middlewares
Split into two categories:
- Static: Applied globally (e.g., body parsers)
- Dynamic: Also applied globally but run per request, with full access to the
req
,res
,next
lifecycle. Dynamic middlewares can be overwritten per request.
middlewares: {
static: [parser.urlencoded({ extended: true }), parser.json()],
dynamic: [
(req, res, next) => {
console.log("Dynamic middleware test");
next();
},
],
},
handlers
Response middleware — custom global middleware for managing server responses:
- Response handler: Formats the output returned by the controller method.
- 404 fallback: Handles requests to routes that don’t exist.
- Global error handler: Catches and formats server errors.
handlers: {
response: (req, res, next) => res.status(200).json(res.locals.data),
notFound: (req, res, next) => res.status(404).json({ error: "Not Found" }),
error: (err, req, res, next) => {
console.error(err);
res.status(500).json({ error: "Internal Server Error" });
},
},
In this framework, controller methods return data directly, which is then passed to the response middleware for formatting and sending to the client.
There is a global try-catch error handler, so you don’t need to repeat error handling inside each controller method.
crud
Defines RESTful behavior for models and custom routes.
crud: {
models: [[Wallet, "wallets"]],
routes: [
{
method: "get",
path: "/test",
middleware: [],
ignore: [],
response: async function (req) {
const y = await this.method.find();
return { y, req: req.originalUrl };
},
},
],
},
Registering CRUD Models (crud.models)
You can register models in two ways inside the crud.models
array:
- Simple model import:
crud:{
models: [Users],
routes: [...]
}
The collection path will be inferred from the model name (e.g., /users).
- **Custom route path:**
```ts
crud:{
models: [[BlogPosts, "blog-posts"]],
routes: [...]
}
You can mix both styles in the array:
crud:{
models: [Users, [BlogPosts, "blog-posts"]],
routes: [...]
}
Custom Routes
In the routes
array, you can define custom API endpoints with full control over the HTTP method, path, middleware, and response.
routes: [
{
method: "get",
path: "/test",
middleware: [],
ignore: [],
response: async function (req) {
const customMethod = await this.method.find();
const mognooseMethod = await this.method.model.find();
return { customMethod, mognooseMethod };
},
},
],
Explanation
-
method: HTTP method like
"get"
,"post"
,"put"
, etc. -
path: The URL path for the route (e.g.,
/test
). -
middleware: An array of middleware functions to run before the route handler.
-
ignore: List of middleware or features to skip for this route.
-
response: An async function that handles the request and returns the response data.
You have access tothis.method
which links to the current model’s methods.
If you want to access the underlying Mongoose model directly, usethis.method.model
.
This setup lets you easily add custom endpoints alongside standard CRUD routes.