2.0.2 • Published 10 months ago

meta-controller v2.0.2

Weekly downloads
76
License
MIT
Repository
github
Last release
10 months ago

GitHub npm

What is meta-controller?

meta-controller is a library for creating NodeJs REST APIs using TypeScript decorators. It is a wrapper for the popular express framework. It's designed to be a lightweight alternative to NestJs.

Installation

Install the meta-controller package from npm. npm install meta-controller

Basic Usage

Create a REST API controller by using the JsonController(<route>) decorator and define routes by using the @Route(<http method>, <path>) decorator. Routes can be synchronous or asynchronous. Route paramaters are automatically transformed (meta-transformer) and validated (meta-validator).

@JsonController("/basic")
class WidgetController {
    @Route(HttpMethod.GET)
    get(): Widget {
        return testWidget;
    }
}

const expressApp = express();
MetaController.useExpressServer(expressApp, {
    isUseCors: true,
    controllerClassTypes: [
        WidgetController
    ]
});
apiServer = http.createServer(expressApp);
apiServer.listen(4500);

Initialization

Pass an instance of express to MetaController.useExpressServer() to initialize meta-controller.

const expressApp = express();
MetaController.useExpressServer(expressApp, {
    // options
});

The following initialization options are available.

OptionDescription
isDebugLog any errors to stdout
routePrefixAdd a global route prefix (e.g. /api)
isUseCorsAdd CORS to all routes
isSaveRawBodyAdd the raw body to the request object (request.rawBody)
controllerClassTypesAn array of class controllers that will be added as express routes)
authorizationHandlerA user supplied function that determines if the request has been authorized
currentUserHandlerA user supplied function that retrieves the user (if any) of the current request
customErrorHandlerA global custom error handler
globalMiddlewareAny optional global middleware

Route Parameters

Controllers may accept all standard REST type parameters. Parameters are automatically transformed or cast to the specified type.

HTTP Request Body

@Route(HttpMethod.POST, "/body")
myRoute(@Body() widget: Widget) {
    // ... business logic
}

Route Parameters

// Example: https://localhost/api/param/5
@Route(HttpMethod.GET, "/param/:id")
myRoute(@Param("id") id: number) {
    // ... business logic    
}

Route Query Parameters

// Example: https://localhost/api/query-param?myQueryParam=test
@Route(HttpMethod.POST, "/query-param")
myRoute(@QueryParam("myQueryParam") myQueryParam: string) {
    // ... business logic    
}

HTTP Request Headers

@Route(HttpMethod.GET, "/header-param")
myRoute(@HeaderParam("TestHeader") testHeader: string) {
    // ... business logic    
}

Authorization

You can require authorization on a per-controller basis by specifying an authorizationHandler() and using the @Authorization() decorator.

const expressApp = express();
MetaController.useExpressServer(expressApp, {
    authorizationHandler: (request, response, roles): boolean => {
        // ... business logic
        // Return true for authorized, false for unauthorized
        return true;
    }
});

@Authorize(["Admin"])
@JsonController("/secure")
class SecureController {
    @Route(HttpMethod.GET, "/protected-route")
    myRoute() {
        // ... business logic
    }
}

If you also add a currentUserHandler() you can inject the current user using the CurrentUser() decorator.

class User {
    userName: string = "TestUser";
}
const testUser = new User();

const expressApp = express();
MetaController.useExpressServer(expressApp, {
    currentUserHandler: (request, response): User => {
        // ... business logic
        return testUser;
    }
});

@Route(HttpMethod.GET, "/current-user")
getCurrentUser(@CurrentUser() currentUser: User): User {
    // ... business logic
    return currentUser;
}

Error Handling

You can throw errors along with associated HTTP error codes.

@Authorize(["Admin"])
@JsonController("/secure")
class SecureController {
    @Route(HttpMethod.GET, "/protected-route")
    myRoute() {
        throw new HttpError(HttpStatus.UNAUTHORIZED, "Unauthorized request");
    }
}

If no HTTP error code is specified then meta-controller defaults to using HTTP status 500 (INTERNAL_SERVER_ERROR).

@Route(HttpMethod.POST, "/body")
myRoute(@Body() widget: Widget) {
    // Returns HTTP status 500 - INTERNAL_SERVER_ERROR
    throw new Error("An unknown error occurred");
}

Decorator Reference

DecoratorTypeDescription
@Authorize()ClassController requires authorization
@JsonController()ClassCreate a JSON controller
@Body()ParameterInject a JSON body parameter
@CurrentUser()ParameterInject the current user
@EncodedJwtToken()ParameterInject the encoded JWT token string
@HeaderParam()ParameterInject a header from the HTTP request
@Param()ParameterInject a route parameter (e.g. /user/:id)
@QueryParam()ParameterInject a query parameter (e.g. /route?my-param=test)
@Request()ParameterInject the entire request object
@Response()ParameterInject the entire response object
@Route(<http method, path>)PropertyDefine a route on the controller
2.0.2

10 months ago

2.0.1

2 years ago

2.0.0

2 years ago

2.0.0-beta.1

2 years ago

1.0.0

2 years ago

0.0.48

2 years ago

0.0.43

2 years ago

0.0.44

2 years ago

0.0.45

2 years ago

0.0.46

2 years ago

0.0.47

2 years ago

0.0.41

3 years ago

0.0.42

3 years ago

0.0.40

3 years ago

0.0.39

3 years ago

0.0.38

3 years ago

0.0.37

3 years ago

0.0.36

3 years ago

0.0.35

3 years ago

0.0.34

3 years ago

0.0.32

3 years ago

0.0.33

3 years ago

0.0.31

3 years ago

0.0.30

3 years ago

0.0.29

3 years ago

0.0.28

3 years ago

0.0.27

3 years ago

0.0.26

3 years ago

0.0.25

3 years ago

0.0.24

4 years ago

0.0.23

4 years ago

0.0.21

4 years ago

0.0.22

4 years ago

0.0.20

4 years ago

0.0.19

4 years ago

0.0.18

4 years ago

0.0.17

4 years ago

0.0.16

4 years ago

0.0.15

4 years ago

0.0.14

4 years ago

0.0.12

4 years ago

0.0.13

4 years ago

0.0.11

4 years ago

0.0.10

4 years ago

0.0.9

4 years ago

0.0.8

4 years ago

0.0.7

4 years ago

0.0.6

4 years ago

0.0.5

4 years ago

0.0.3

4 years ago

0.0.2

4 years ago

0.0.4

4 years ago

0.0.1

4 years ago