alamanah-express v2.3.2
Al Amanah
Taking inspiration from Django, Al Amanah uses express to implement a basic routing system & add some more functionality.
- Al Amanah comes in especially useful when needing to quickly initialize a REST API.
Setup
- Run
npm install alamanah-expressto install the npm package - Use the
alamanah-clito quickly start a new project (Optional)
Starting a Server
All you need to start a server, is a port and an array of routes.
import alamanah, { route } from "alamanah-express";
const routes = [
route({ path: '/hello', method: "GET", view: (req, res) => res.send("Hello world!") }),
route({ path: '/goodbye', method: "GET", view: (req, res) => res.send("Goodbye world!") }),
]
const server = alamanah({
port: 5000,
routes
});Routing
Import the route function from the alamanah-express module to use the routing system.
The route function takes in one of two objects, an EndRoute object or a BaseRoute object.
EndRoute objects are your standard URL endpoints, whereas BaseRoute objects are routers to those endpoints.
Creating an EndRoute:
To create an EndRoute, pass in the path, method and view parameters.
const route = route({ path: '/hello', method: "GET", view: (req, res) => res.send("Hello world!") });Creating a BaseRoute:
To create a BaseRoute, pass in the path and routes parameters.
const routes = [route1, route2, route3];
const base = route({ path: '/hello', routes: routes });Mixing EndRoutes and BaseRoutes
import alamanah, { route } from "alamanah-express";
const helloRoutes = [
route({ path: '/world', method: "GET", view: (req, res) => res.send("Hello world!") }),
route({ path: '/people', method: "GET", view: (req, res) => res.send("Hello people!") }),
]
const routes = [
route({ path: '/hello', routes: helloRoutes }),
route({ path: '/goodbye', method: "GET", view: (req, res) => res.send("Goodbye world!") }),
]
const server = alamanah({
port: 5000,
routes
});The /hello route in this example, is now a BaseRoute, since it takes in an array of routes.
The /goodbye route is still an EndRoute.
Now our server has the following URL endpoints,
GET /hello/worldGET /hello/peopleGET /goodbye
Applying Middleware
You can apply express middleware by putting them into an array and passing them to the server.
...
const logger = (req, res, next) => {
console.log(req.ip);
next();
}
const middleware = [
logger
]
const server = alamanah({
port: 5000,
routes,
middleware
});