- Notifications
You must be signed in to change notification settings - Fork0
A light-weight library to help you create APIs on the fly using express.js written in TypeScript
NotificationsYou must be signed in to change notification settings
naseif/API-Tools-TS
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
A modern, type-safe, light-weight library to help you create APIs quickly using Express.js, written in TypeScript.
- Type-safe: Full TypeScript support with comprehensive type definitions
- Easy to use: Simplified Express.js API for beginners
- Flexible: Support for middleware, parameter validation, and bulk route registration
- Modern: Promise-based with async/await support
- Secure: Built-in security middlewares (helmet, cors)
- Configurable: Extensive configuration options
npm install api-tools-ts
import{APIController}from"api-tools-ts";constapi=newAPIController("/api/v1",{port:3000,useDefaultMiddlewares:true});api.addEndpoint("/","get",(req,res)=>{res.json({message:"Hello World!"});});awaitapi.startServer();
const{ APIController}=require("api-tools-ts");constapi=newAPIController("/api/v1");api.addEndpoint("/","get",(req,res)=>{res.json({message:"Hello World!"});});api.startServer();
import{APIController}from"api-tools-ts";constapi=newAPIController("/api/v1");// Simple GET endpointapi.addEndpoint("/","get",(req,res)=>{res.json({message:"Welcome to the API!"});});// Parameterized endpointapi.addEndpoint("/users/:id","get",(req,res)=>{constuserId=req.params.id;res.json({ userId,message:`User${userId} profile`});});awaitapi.startServer();
import{APIController}from"api-tools-ts";constapi=newAPIController("/api/v1");constgetUsers=(req,res)=>{res.json({users:[],message:"All users"});};constcreateUser=(req,res)=>{res.status(201).json({message:"User created",user:req.body});};constdeleteUser=(req,res)=>{res.json({message:"User deleted"});};api.addMultipleMethods("/users",["get","post","delete"],[getUsers,createUser,deleteUser]);awaitapi.startServer();
import{APIController,RouteDefinition}from"api-tools-ts";constapi=newAPIController("/api/v1");constroutes:RouteDefinition[]=[{path:"/users",method:"get",handler:(req,res)=>res.json({users:[]})},{path:"/users",method:"post",handler:(req,res)=>res.status(201).json({user:req.body})},{path:"/health",method:["get","head"],handler:[(req,res)=>res.json({status:"ok"}),(req,res)=>res.status(200).end()]}];api.addRoutes(routes);awaitapi.startServer();
import{APIController}from"api-tools-ts";constapi=newAPIController("/api/v1");// Add custom middlewareapi.addMiddleware("logger",(req,res,next)=>{console.log(`${newDate().toISOString()} -${req.method}${req.path}`);next();});// Add authentication middlewareapi.addMiddleware("auth",(req,res,next)=>{consttoken=req.headers.authorization;if(!token){returnres.status(401).json({error:"Token required"});}next();});api.addEndpoint("/protected","get",(req,res)=>{res.json({message:"This is a protected route"});});awaitapi.startServer();
import{APIController}from"api-tools-ts";constapi=newAPIController("/api/v1");// Add parameter validationapi.addParamChecker("id",(req,res,next,value)=>{constid=parseInt(value);if(isNaN(id)||id<=0){returnres.status(400).json({error:"Invalid ID parameter"});}req.params.id=id.toString();// Normalize the parameternext();});api.addEndpoint("/users/:id","get",(req,res)=>{res.json({userId:req.params.id,message:"Valid user ID"});});awaitapi.startServer();
import{APIController}from"api-tools-ts";constapi=newAPIController("/api/v1",{port:8080,hostname:"0.0.0.0",useDefaultMiddlewares:true,cors:{origin:["http://localhost:3000","https://yourdomain.com"],credentials:true},helmet:{contentSecurityPolicy:false},morgan:"combined",jsonLimit:"50mb"});awaitapi.startServer();
import{APIController,ControllerErrors,Errors}from"api-tools-ts";constapi=newAPIController("/api/v1");api.addEndpoint("/error-demo","get",(req,res)=>{// The library will automatically handle ControllerErrorsthrownewControllerErrors("Something went wrong",Errors.CONTROLLER_ERROR,{timestamp:Date.now(),endpoint:"/error-demo"});});awaitapi.startServer();
import{APIController}from"api-tools-ts";constapi=newAPIController("/api/v1");api.addEndpoint("/","get",(req,res)=>{res.json({message:"Hello World!"});});// Start the serverawaitapi.startServer();// Get server informationconsole.log(api.getServerInfo());// Output: { port: 3000, hostname: 'localhost', mainEndPoint: '/api/v1', isRunning: true }// Check active connectionsconsole.log(`Active connections:${api.getActiveConnections()}`);// Gracefully stop the serverawaitapi.stopServer();// Restart the serverawaitapi.restartServer();// Force stop (for emergencies)api.forceStopServer();
import{APIController}from"api-tools-ts";constapi=newAPIController("/api/v1");// Set up your routesapi.addEndpoint("/","get",(req,res)=>{res.json({message:"API is running"});});awaitapi.startServer();// Handle graceful shutdown on process signalsprocess.on('SIGTERM',async()=>{console.log('SIGTERM received, shutting down gracefully');try{awaitapi.stopServer();process.exit(0);}catch(error){console.error('Error during shutdown:',error);process.exit(1);}});process.on('SIGINT',async()=>{console.log('SIGINT received, shutting down gracefully');try{awaitapi.stopServer();process.exit(0);}catch(error){console.error('Error during shutdown:',error);process.exit(1);}});
newAPIController(endpoint: string,config?:APIControllerConfig)
interfaceAPIControllerConfig{port?:number;// Default: 3000hostname?:string;// Default: 'localhost'useDefaultMiddlewares?:boolean;// Default: truecors?:cors.CorsOptions;// CORS configurationhelmet?:HelmetOptions;// Helmet configurationmorgan?:string|FormatFn;// Morgan logging formatjsonLimit?:string;// JSON payload limiturlEncodedLimit?:string;// URL encoded payload limit}
addEndpoint(path, method, callback, middlewares?)
- Add a single endpointaddMultipleMethods(path, methods, callbacks)
- Add multiple methods to one pathaddRoutes(routes)
- Bulk register routesaddMiddleware(id, callback)
- Add middlewareaddParamChecker(param, callback)
- Add parameter validationstartServer(config?)
- Start the serverstopServer()
- Stop the server gracefullyforceStopServer()
- Force stop the server immediatelyrestartServer()
- Restart the servergetServerInfo()
- Get server statusgetEndpoints()
- Get all registered endpointsgetActiveConnections()
- Get current connection count
AddEndPoint()
- Legacy version of addEndpointAddMultipleMethods()
- Legacy version of addMultipleMethodsAddMiddleWare()
- Legacy version of addMiddlewareAddParamChecker()
- Legacy version of addParamChecker
WhenuseDefaultMiddlewares
is true (default), the following middlewares are automatically applied:
- Morgan: HTTP request logger
- Helmet: Security headers
- CORS: Cross-origin resource sharing
- Express.json(): JSON body parser
- Express.urlencoded(): URL encoded body parser
The library maintains backward compatibility, but we recommend migrating to the new API:
// Old way (still works)api.AddEndPoint("/users","get",callback);// New way (recommended)api.addEndpoint("/users","get",callback);
Contributions are welcome! Please feel free to submit a Pull Request.
MIT License - see theLICENSE file for details.
- ✨ Modern async/await API
- 🔒 Improved type safety
- 🛡️ Better error handling
- 📦 Bulk route registration
- ⚙️ Advanced configuration options
- 🔄 Backward compatibility maintained
About
A light-weight library to help you create APIs on the fly using express.js written in TypeScript
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
No releases published
Packages0
No packages published
Uh oh!
There was an error while loading.Please reload this page.