restifyx.js
TypeScript icon, indicating that this package has built-in type declarations

1.0.30 • Public • Published

RestifyX.js

License: MIT npm version TypeScript

A modern, feature-rich, and highly configurable REST API framework built on top of Express.js with built-in TypeScript support.

Features

  • 🚀 Express.js Powered: Built on the solid foundation of Express.js
  • 🔒 Security First: Built-in security features including CORS, Helmet, rate limiting, and more
  • 📝 Swagger Integration: Automatic API documentation generation
  • 🔄 Hot Reload: Development mode with automatic endpoint reloading
  • 🧩 Middleware Support: Pre-built middleware and easy custom middleware integration
  • 🌐 WebSocket Support: Built-in Socket.IO integration
  • Validation: Request validation with Joi
  • 🔍 Error Handling: Comprehensive error handling system
  • 📊 Logging: Configurable logging with Winston
  • 🧪 Testing Ready: Easy to test with popular testing frameworks
  • 🔌 Plugin System: Extensible plugin architecture
  • 🔄 Hot Reload: Development mode with automatic endpoint reloading

Installation

# Using npm
npm install restifyx.js

# Using yarn
yarn add restifyx.js

# Using pnpm
pnpm add restifyx.js

Quick Start

TypeScript

import { create } from 'restifyx.js';
import { CreateEndpoint, SendData } from 'restifyx.js';

// Create a new endpoint
const helloEndpoint = CreateEndpoint()
  .setName('Hello World')
  .setPath('/hello')
  .setMethod('GET')
  .setHandler(async () => {
    SendData.json({ message: 'Hello, World!' });
  });

// Create and configure the application
const app = create({
  port: 3000,
  debug: true
});

// Register the endpoint
app.registerEndpoint(helloEndpoint.build());

// Start the server
async function start() {
  await app.setup();
  await app.start();
}

start().catch(console.error);

JavaScript

const { create } = require('restifyx.js');
const { CreateEndpoint, SendData } = require('restifyx.js');

// Create a new endpoint
const helloEndpoint = CreateEndpoint()
  .setName('Hello World')
  .setPath('/hello')
  .setMethod('GET')
  .setHandler(async () => {
    SendData.json({ message: 'Hello, World!' });
  });

// Create and configure the application
const app = create({
  port: 3000,
  debug: true
});

// Register the endpoint
app.registerEndpoint(helloEndpoint.build());

// Start the server
async function start() {
  await app.setup();
  await app.start();
}

start().catch(console.error);

Configuration

RestifyX.js is highly configurable. Here's an example of a full configuration:

import { create } from 'restifyx.js';

const app = create({
  port: 3000,
  host: '0.0.0.0',
  debug: true,
  strictMode: false,
  
  endpoints: {
    directory: 'src/endpoints',
    pattern: '**/*.endpoint.{js,ts,mjs,cjs}',
    autoRegister: true,
    dynamicImport: true
  },
  
  cors: {
    enabled: true,
    options: {
      origin: '*',
      methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
      allowedHeaders: ['Content-Type', 'Authorization']
    }
  },
  
  // ... other configuration options
});

Hot Reload

RestifyX.js includes a powerful hot reload system that automatically detects changes to your endpoint files and reloads them without restarting the server. This feature significantly speeds up development by eliminating the need to restart your server after each code change.

Configuration

The hot reload feature can be configured with the following options:

import { create } from 'restifyx.js';

const app = create({
  // ... other configuration options
  
  hotReload: {
    enabled: true,                                // Enable/disable hot reload
    debounceMs: 500,                              // Debounce time for file changes
    watchExtensions: ['.js', '.ts', '.mjs', '.cjs'], // File extensions to watch
    ignorePatterns: ['node_modules', '.git', 'dist'], // Patterns to ignore
    watchNodeModules: false,                      // Whether to watch node_modules
    verbose: false                                // Enable detailed logging
  }
});

TypeScript Example

// src/index.ts
import { create } from 'restifyx.js';

const app = create({
  port: 3000,
  debug: true,
  hotReload: {
    enabled: true,
    verbose: true
  }
});

async function start() {
  await app.setup();
  await app.start();
}

start().catch(console.error);

// src/endpoints/hello.endpoint.ts
import { CreateEndpoint, SendData } from 'restifyx.js';

export default CreateEndpoint()
  .setName('Hello World')
  .setPath('/hello')
  .setMethod('GET')
  .setHandler(async () => {
    SendData.json({ message: 'Hello, World!' });
  });

JavaScript Example

// src/index.js
const { create } = require('restifyx.js');

const app = create({
  port: 3000,
  debug: true,
  hotReload: {
    enabled: true,
    verbose: true
  }
});

async function start() {
  await app.setup();
  await app.start();
}

start().catch(console.error);

// src/endpoints/hello.endpoint.js
const { CreateEndpoint, SendData } = require('restifyx.js');

module.exports = CreateEndpoint()
  .setName('Hello World')
  .setPath('/hello')
  .setMethod('GET')
  .setHandler(async () => {
    SendData.json({ message: 'Hello, World!' });
  });

How Hot Reload Works

  1. File Watching: RestifyX.js watches your endpoints directory for file changes.
  2. Change Detection: When a file is modified, added, or deleted, the hot reload system detects the change.
  3. Module Cache Clearing: The system clears the Node.js module cache for the changed files.
  4. Endpoint Reloading: All endpoints are re-registered with the updated code.
  5. Immediate Effect: Your changes take effect immediately without restarting the server.

Advanced Hot Reload Configuration

For more advanced use cases, you can configure the hot reload system with additional options:

import { create } from 'restifyx.js';

const app = create({
  // ... other configuration options
  
  hotReload: {
    enabled: true,
    debounceMs: 300,                              // Faster response to changes
    watchExtensions: ['.js', '.ts', '.json'],     // Also watch JSON files
    ignorePatterns: [
      'node_modules',
      '.git',
      'dist',
      'test',                                     // Ignore test files
      'temp'                                      // Ignore temporary files
    ],
    watchNodeModules: false,
    verbose: true                                 // Enable detailed logging
  }
});

Best Practices for Hot Reload

  1. Use Modular Code: Organize your code into small, focused modules for better hot reload performance.
  2. Avoid Global State: Minimize the use of global state that might be affected by hot reloading.
  3. Handle Cleanup: If your endpoints create resources (like timers or connections), make sure they clean up properly when reloaded.
  4. Enable Verbose Logging During Development: Set verbose: true to get detailed logs about the hot reload process.
  5. Adjust Debounce Time: If you experience too many reloads, increase the debounceMs value.

Troubleshooting Hot Reload

If you encounter issues with hot reload:

  1. Check File Patterns: Ensure your endpoint files match the pattern specified in the configuration.
  2. Verify File Permissions: Make sure the process has read permissions for the watched files.
  3. Check for Syntax Errors: Syntax errors can prevent successful reloading.
  4. Increase Log Level: Set the logging level to debug for more detailed information.
  5. Check for File Lock Issues: Some editors or tools might lock files, preventing proper watching.

Endpoint Creation

RestifyX.js provides a fluent API for creating endpoints:

import { CreateEndpoint, SendData } from 'restifyx.js';

const userEndpoint = CreateEndpoint()
  .setName('Get User')
  .setDescription('Get user by ID')
  .setPath('/api/users/:id')
  .setMethod('GET')
  .setTags(['users'])
  .addParams({
    id: {
      type: 'string',
      required: true
    }
  })
  .addResponse({
    200: { user: { id: '123', name: 'John Doe' } },
    404: 'User not found'
  })
  .setHandler(async (header, body, query, cookie, params) => {
    // Get user by ID
    const user = { id: params.id, name: 'John Doe' };
    SendData.json({ user });
  });

export default userEndpoint;

Middleware

RestifyX.js supports middleware at both the application and endpoint levels:

import { create } from 'restifyx.js';
import { CreateEndpoint } from 'restifyx.js';

// Application-level middleware
const app = create({
  middleware: {
    before: [
      (req, res, next) => {
        console.log('Request received');
        next();
      }
    ],
    after: [
      (req, res, next) => {
        console.log('Response sent');
        next();
      }
    ]
  }
});

// Endpoint-level middleware
const protectedEndpoint = CreateEndpoint()
  .setPath('/protected')
  .setMethod('GET')
  .addMiddleware(
    (req, res, next) => {
      if (!req.headers.authorization) {
        return res.status(401).json({ message: 'Unauthorized' });
      }
      next();
    }
  )
  .setHandler(async () => {
    // Handler code
  });

Error Handling

RestifyX.js provides a comprehensive error handling system:

import { ApiError, SendData } from 'restifyx.js';

// In an endpoint handler
try {
  // Some code that might throw an error
  if (!user) {
    throw ApiError.notFound('User not found');
  }
  
  SendData.json({ user });
} catch (error) {
  // The error will be caught by the global error handler
  throw error;
}

WebSocket Support

RestifyX.js includes built-in WebSocket support via Socket.IO:

import { create } from 'restifyx.js';

const app = create({
  websocket: {
    enabled: true,
    path: '/socket.io',
    cors: {
      origin: '*',
      methods: ['GET', 'POST']
    }
  }
});

// After starting the server
const io = app.getWebSocketManager().getIO();

io.on('connection', (socket) => {
  console.log('Client connected');
  
  socket.on('message', (data) => {
    console.log('Message received:', data);
    socket.emit('response', { received: true });
  });
});

Validation

RestifyX.js includes request validation using Joi:

import { CreateEndpoint, SendData } from 'restifyx.js';

const createUserEndpoint = CreateEndpoint()
  .setPath('/api/users')
  .setMethod('POST')
  .addBody({
    name: {
      type: 'string',
      required: true,
      min: 3
    },
    email: {
      type: 'string',
      required: true,
      pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    },
    age: {
      type: 'number',
      min: 18
    }
  })
  .setHandler(async (header, body) => {
    // Body is already validated
    SendData.json({ user: { id: '123', ...body } });
  });

Swagger Documentation

RestifyX.js automatically generates Swagger documentation for your API:

import { create } from 'restifyx.js';

const app = create({
  swagger: {
    enabled: true,
    title: 'My API',
    description: 'My API Description',
    version: '1.0.0',
    path: '/api-docs'
  }
});

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Package Sidebar

Install

npm i restifyx.js

Weekly Downloads

186

Version

1.0.30

License

MIT

Unpacked Size

569 kB

Total Files

123

Last publish

Collaborators

  • wintxr.dev