@djoerkie/routify
v1.0.6
Published
Api router based on folders and file names.
Downloads
16
Readme
Features 🚀
- Routes are file and folder based
- Params are supported
- Routes can be nested
Installation 📦
The project requires a working node.js installation, if you do not have it installed please do this first.
npm install djoerkie@routify
Usage 📚
import { routify } from "@djoerkie/routify";
const routify_instance = new routify(3000); // 3000 is the port
routify_instance.init('./routes'); // './routes' is the folder where the routes are located
You can now make a folder called 'routes' and put files/folders inside it. The file/folder names will be used as the route.
export default function get(res: any, req: any) {
res.json({ message: "Hello World!" });
}
You can rename the function 'get' to one of the following names:
- get
- post
- put
- delete
- patch
- options
- head
This example will make the route postable.
export default function post(res: any, req: any) {
res.json({ message: "Hello World!" });
}
You can make a new folder and put routes inside it. The folder name will be used as the route prefix and the routes inside the folder will be accessible. For example:
/api/hello
will need a folder calledapi
and a file calledhello.ts/js
You can also use a '.' in the file name to make a subroute. For example:
/api/hello/world
will need a folder calledapi
and a file calledhello.world.ts/js
Parameters
You can add params to the route by surrounding the file name with '[param]', for example [userid] will be hosted at localhost:port/userid and the param will be available in the request object.
export default function get(res: any, req: any) {
res.json({ message: req.params.userid });
}
Adding modules
You can add middleware to the app by adding it in the options object while initializing the app.
import { routify } from "@djoerkie/routify";
const routify_instance = new routify(3000);
routify_instance.init('./routes', {
middleware: [
(req: any, res: any, next: any) => {
console.log("Middleware 1");
next();
}
]
});
Or pass body-parser for example:
import { routify } from "@djoerkie/routify";
const routify_instance = new routify(3000);
routify_instance.init('./routes', {
middleware: [
bodyParser.json(),
bodyParser.urlencoded({ extended: true }),
]
});
Getting info
You can get the express app object by calling the getApp method.
import { routify } from "@djoerkie/routify";
const routify_instance = new routify(3000);
routify_instance.init('./routes');
const app = routify_instance.getApp();
You can get the routes object by calling the getRoutes method.
import { routify } from "@djoerkie/routify";
const routify_instance = new routify(3000);
routify_instance.init('./routes');
const routes = routify_instance.getRoutes();
You can get the port by calling the getPort method.
import { routify } from "@djoerkie/routify";
const routify_instance = new routify(3000);
routify_instance.init('./routes');
const port = routify_instance.getPort();
License 📝
MIT © djoerkie