Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

mvc-middleware

Package Overview
Dependencies
Maintainers
1
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mvc-middleware

Mvc middleware for express with API similar to .NET MVC

  • 3.0.0-alpha.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
7
increased by133.33%
Maintainers
1
Weekly downloads
 
Created
Source

mvc-middleware

Mvc middleware for express like .Net Mvc

license npm latest package codecov

How to use

// src/index.ts
import { container } from "cheap-di";
import express, { Router } from 'express';
import { MvcMiddleware } from 'mvc-middleware';

const app = express();

// Path to folder where you have you controllers.
// Middleware will search controlelrs recursively.
// Each file with '.ts' extension and default export and 
//  typeof === 'function', decorated with '@api' will be
//  assumed as controller class.
const controllersPath = path.join(__dirname, "api");

new MvcMiddleware(app, container /* dependency injection */)
  .registerControllers(controllersPath);

// ... run your server ...

You may pass any custom DI resolver that implements following contract:

type AbstractConstructor<T = any> = abstract new (...args: any[]) => T;
type Constructor<T = any> = new (...args: any[]) => T;

type Resolver = <TInstance>(type: Constructor<TInstance> | AbstractConstructor<TInstance>, ...args: any[]) => TInstance | undefined;

interface DependencyResolver {
  /** instantiate by class */
  resolve: Resolver;
}

We have two sets of decorators: for stage 2 (legacy) and stage 3 proposals. You may choose one of them with imports:

import { api, GET, POST, PUT, PATCH, DELETE } from 'mvc-middleware/stage2';
import { api, GET, POST, PUT, PATCH, DELETE } from 'mvc-middleware/stage3';
// src/api/UsersController.ts
import { Request, Response } from 'express';
import { api, GET, POST } from 'mvc-middleware/stage2';

@api('/api/user')
export class UsersController extends MvcController {
  static users: Array<{ id: number, name: string }> = [{
    id: 1,
    name: 'user 1',
  }]

  constructor(request: Request, response: Response) {
    super(request, response);
  }

  // GET: /api/users/list
  @GET
  list() {
    return this.ok(UsersController.users);
  }

  // GET: /api/users/:userId
  @GET(':userId')
  getById(userIdStr: string) {
    const userId = parseInt(userIdStr, 10);
    const user = UsersController.users.find(user => user.id === userId);
    return this.ok(user);
  }

  // POST: /api/users/add
  @POST
  add({ name }: { name: string }) {
    UsersController.users.push({
      id: UsersController.users.length + 1,
      name,
    });
    return this.ok('user is added');
  }
}

export default UsersController;

If you want to get query params and body content you have to connect another middlewares, that will handle requests before MvcMiddleware like bellow.

// src/index.ts
import express, { Router } from 'express';
import bodyParser from 'body-parser';
import { MvcMiddleware } from 'mvc-middleware';

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());

// ...

MvcController methods

Method nameResponse status codeResponse typeArgumentsDescription
ok200text or jsonmodel?: anyreturns 200 status code with data
created201text or jsonmodel?: anyreturns 201 status code with data
accepted202text or jsonmodel?: anyreturns 202 status code with data
noContent204--returns 204 status code
found302texturl: stringreturns 302 status code
permanentRedirect308texturl: stringreturns 308 status code
redirect300 - 308textstatusCode: number, url: stringreturns redirection status code
badRequest400text or jsonmodel?: anyreturns 400 status code with data
unauthorized401text or jsonmodel?: anyreturns 401 status code with data
forbid403-model?: anyreturns 403 status code
notFound404text or jsonmodel?: anyreturns 404 status code with data
conflict409text or jsonmodel?: anyreturns 409 status code with data
serverError500textmessage?: anyreturns 500 status code with error message
sendResponseany http status codetextmodel: any, statusCode?: numberreturns status code with data. Default status code is 200

Keywords

FAQs

Package last updated on 15 Dec 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc