# rokot-apicontroller

> Api Controller generation for express

Latest version **0.7.5** (published 2021-07-09) · MIT license · 0 weekly downloads

## Install

```sh
npm install rokot-apicontroller
pnpm add rokot-apicontroller
yarn add rokot-apicontroller
bun add rokot-apicontroller
```

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.7.5 |
| Published | 2021-07-09 |
| First published | 2016-08-19 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 3 |
| Unpacked size | 86 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | developers@rocketmakers.com |
| Maintainers | sheamurphy1919, rocketsoper, joerocketmakers, rocketmakers-admin, adamrocketmakers, david.haylock |
| Keywords | typescript, express, api |

## Links

- npm: https://www.npmjs.com/package/rokot-apicontroller
- Repository: https://git@gitlab.com:rocketmakers/rokot/apicontroller
- Homepage: https://gitlab.com/rocketmakers/rokot/apicontroller
- Issues: https://gitlab.com/rocketmakers/rokot/apicontroller/issues
- npm.io page: https://npm.io/package/rokot-apicontroller

## Dependencies (3)

- [underscore](https://npm.io/package/underscore.md) ^1.9.1
- [path-to-regexp](https://npm.io/package/path-to-regexp.md) ^1.7.0
- [reflect-metadata](https://npm.io/package/reflect-metadata.md) ^0.1.13

## Alternatives

- [@openai/codex-sdk](https://npm.io/package/@openai/codex-sdk.md) — 731.4K weekly downloads
- [babel-plugin-transform-react-jsx](https://npm.io/package/babel-plugin-transform-react-jsx.md) — 565.0K weekly downloads
- [babel-helper-remove-or-void](https://npm.io/package/babel-helper-remove-or-void.md) — 508.5K weekly downloads
- [@pnpm/store-controller-types](https://npm.io/package/@pnpm/store-controller-types.md) — 186.9K weekly downloads
- [react-native-signature-canvas](https://npm.io/package/react-native-signature-canvas.md) — 155.6K weekly downloads

## Recent versions

- 0.7.5 (latest) — 2021-07-09
- 0.7.4 — 2021-05-21
- 0.7.3 — 2021-05-21
- 0.7.2 — 2020-02-24
- 0.7.1 — 2019-11-13
- 0.7.0 — 2019-10-08
- 0.6.1 — 2019-10-03
- 0.6.0 — 2019-10-02
- 0.5.23 — 2019-09-12
- 0.5.22 — 2019-06-12
- 0.5.21 — 2019-05-28
- 0.5.20 — 2019-02-15
- 0.5.19 — 2018-12-18
- 0.5.18 — 2018-03-27
- 0.5.17 — 2018-03-07
- … 42 more at https://npm.io/package/rokot-apicontroller/versions

## README

# rokot-apicontroller

Rokot - [Rocketmakers](http://www.rocketmakers.com/) TypeScript NodeJs Platform

## Introduction

A typescript decorators based solution to declaratively define routes for REST based api
This library creates metadata about the defined routes to allow auto route generation

## Getting Started

### Installation
Install via `npm`
```
npm i rokot-apicontroller
```

## Example

If you want to specify any additional custom Middleware, you can define them as below and annotate with the `middleware` decorator

```typescript
import { api } from "rokot-apicontroller";

class Middleware {
  @api.middlewareFunction("one")
  static one = (req: Express.Request, res: Express.Response, next: () => void) => {
    console.log("one")
    next();
  }
  @api.middlewareFunction("two")
  static two(req: Express.Request, res: Express.Response, next: () => void) {
    console.log("two")
    next();
  }
  @api.middlewareFunction("three")
  three(req: Express.Request, res: Express.Response, next: () => void) {
    console.log("three")
    next();
  }

  @api.middlewareProviderFunction("logger", 1)
  static logger(log: string) {
    return (req: Express.Request, res: Express.Response, next: () => void) => {
      console.log(log, req)
      next();
    }
  }

  @api.middlewareProviderFunction("simplelogger", 0, 1)
  static simplelogger(log?: string) {
    return (req: Express.Request, res: Express.Response, next: () => void) => {
      console.log(log || "Unknown", req)
      next();
    }
  }
}
```

You can optionally register the middleware directly via the `registerMiddlewareFunction` method

```typescript
import { registerMiddlewareFunction } from "rokot-apicontroller";

registerMiddlewareFunction("four", (req: Express.Request, res: Express.Response, next: () => void) => {
  console.log("four")
  next();
})
```

You can optionally create your own request to shape the request handler object:

```typescript
import { IExpressApiRequest, ExpressRouteBuilder, ExpressApiRequest, IExpressRequest } from "rokot-apicontroller";

export interface IUser {
  id: string;
  userName: string
}

export interface IRequest<TBody, TResponse, TParams, TQuery> extends IExpressApiRequest<TBody, TResponse, TParams, TQuery> {
  isAuthenticated(): boolean
  isUnauthenticated(): boolean
  user: IUser
}

export interface IGetRequest<TResponse, TParams, TQuery> extends IRequest<void, TResponse, TParams, TQuery> {
}

export class CustomExpressApiRequest<TBody, TResponse, TParams, TQuery>
  extends ExpressApiRequest<TBody, TResponse, TParams, TQuery>
  implements IRequest<TBody, TResponse, TParams, TQuery> {
  user: IUser
  constructor(native: IExpressRequest) {
    super(native)
    this.user = native.request["user"];
  }
  isAuthenticated(): boolean {
    return this.native.request["isAuthenticated"]()
  }
  isUnauthenticated(): boolean {
    return this.native.request["isUnauthenticated"]()
  }
}

export class CustomExpressRouteBuilder extends ExpressRouteBuilder {
  protected createHandler(req: IExpressRequest) {
    return new CustomExpressApiRequest<any, any, any, any>(req)
  }
}
```


You can then specify controllers and their routes:

```typescript
import { api } from "rokot-apicontroller";
import { IRequest, IGetRequest, IUser } from "./customRequest"; // from file above


interface IGroup {
  id: string;
  name: string;
  members: IUser[];
}

/*
Register the MiddlewareController
: all route paths are prefixed with "/middleware"
: all routes use the middleware function "one"
  then the resolved middleware via provider "logger"
  (using "MiddlewareController" as the required param)
*/
@api.controller("MiddlewareController", "/middleware", b => b.add("one").add("logger", "MiddlewareController"))
class MiddlewareController {

  @api.route(":id")
  @api.verbs("get", "options")
  @api.middleware("two")
  @api.middleware("three")
  get(req: IGetRequest<IGroup, { id: string }, void>) {
    req.sendOk({ id: req.params.id, name: "group", members: [{ id: "1", userName: "User 1" }] });
  }

  @api.route()
  @api.verbs("get", "options")
  getAll(req: IGetRequest<IGroup[], void, void>) {
    req.sendOk([
      { id: "1", name: "group", members: [{ id: "1", userName: "User 1" }] }
    ]);
  }

  @api.route()
  @api.contentType("application/x-www-form-urlencoded")
  post(req: IRequest<IGroup, IGroup, void, void>) {
    req.sendCreated(req.body);
  }

  @api.route(":id")
  delete(req: IGetRequest<void, { id: string }, void>) {
    var id = req.params.id;
    req.sendNoContent()
  }
}
```

To build your routes (and bootstrap your api) you can

```typescript
import { CustomExpressRouteBuilder } from "./customRequest"; // from file above
import { ApiBuilder, apiControllers, middlewareFunctions } from "rokot-apicontroller";
import { ConsoleLogger } from "rokot-log";
import * as express from 'express';

export function boot(port: number) {
  const app = express();
  const logger = ConsoleLogger.create("Api Routes", { level: "trace" });

  const apiBuilder = new ApiBuilder(logger)
  const runtimeApi = apiBuilder.buildRuntime(apiControllers, middlewareFunctions)
  if (runtimeApi.errors && runtimeApi.errors.length) {
    console.log("Unable to build api model - Service stopping!")
    return;
  }

  const builder = new CustomExpressRouteBuilder(logger, app);
  const ok = builder.build(runtimeApi);
  if (!ok) {
    console.log("Unable to build express routes - Service stopping!")
    return;
  }

  app.listen(port, () => {
    console.log(`Server listening on port ${port}!`);
  });
}
```

### Validation

`rokot-apicontroller` is agnostic of which validation framework you want to use.
You can specify a validation `spec` for the body, queryString or route params (typed as `any`) using:

```
@api.bodyValidationSpec({/* your body spec */})
@api.paramsValidationSpec({/* your route params spec */})
@api.queryValidationSpec({/* your query spec */})
```

Here is an example using the `rokot-validate` package

```typescript
import { api } from "rokot-apicontroller";
import { IRequest, IUser } from "./customRequest"; // from file above
import { createClientConstraintSpec } from "rokot-validate";

interface IRequireValidation {
  id: string;
  name: string;
  members: IUser[];
}

const bodySpec = createClientConstraintSpec<IRequireValidation>(b => {
  return {
    id: { absence: true },
    name: b.stringMandatory(),
    members: b.arrayValidator<IUser>({ id: b.stringMandatory(), userName: b.stringMandatory() })
  }
})

@api.controller("ValidatedController", "/validated")
class ValidatedController {

  @api.route()
  @api.bodyValidationSpec(bodySpec)
  post(req: IRequest<IRequireValidation, IRequireValidation, void, void>) {
    req.sendCreated(req.body);
  }
}
```

You then need to modify your bootstrap to add a validation function (that will validate the payload via its spec and return a validated copy of the payload) to the RouteBuilder constructor

```typescript
import { CustomExpressRouteBuilder } from "./customRequest"; // from file above
import { ApiBuilder, apiControllers, middlewareFunctions } from "rokot-apicontroller";
import { ConsoleLogger } from "rokot-log";
import * as express from 'express';
import { Validation, ClientConstraintSpec } from "rokot-validate";

/* part will be "body" | "params" | "query" */
function validate<T>(spec: ClientConstraintSpec<T>, item: any, part: string) {
  return Validation.executeClient<T>(item, spec)
}

export function boot(port: number) {
  const app = express();
  const logger = ConsoleLogger.create("Api Routes", { level: "trace" });

  const apiBuilder = new ApiBuilder(logger)
  const runtimeApi = apiBuilder.buildRuntime(apiControllers, middlewareFunctions)
  if (runtimeApi.errors && runtimeApi.errors.length) {
    console.log("Unable to build api model - Service stopping!")
    return;
  }

  const builder = new CustomExpressRouteBuilder(logger, app, undefined, validate);
  const ok = builder.build(runtimeApi);
  if (!ok) {
    console.log("Unable to build express routes - Service stopping!")
    return;
  }

  app.listen(port, () => {
    console.log(`Server listening on port ${port}!`);
  });
}
```

If you want to expose these validation `spec`'s to your client, you can add a controller like this!

```typescript
import { api, validationSpecDictionary, IStringDictionary, IRouteValidationSpec } from "rokot-apicontroller";
import { IGetRequest } from "./customRequest"; // from file above

@api.controller("ValidationSpecController", "validationSpec")
class ValidationSpecController {
  @api.route()
  get(req: IGetRequest<IStringDictionary<IRouteValidationSpec>, void, void>) {
    req.send(200, validationSpecDictionary)
  }
}
```

### Notes
The route methods should be instance members, and have a single param `req` of type `IApiRequest<TBody,TResponse,TParams,TQuery,TNative>`
It strongly types all aspects of the request to make consuming them simpler within the route


There is a corresponding `IExpressApiRequest<TBody, TResponse, TParams, TQuery>` that supplies the `TNative` with `{ request: express.Request, response: express.Response, next: express.NextFunction }`

The `@api.controller` decorator allows you to specify a controller name, route path prefix, and optionally the middleware keys to apply to all the controller contained routes.

NOTE: Its strongly recommended to supply the name of the class as the first parameter of `@api.controller`

The `@api.route` decorator must be supplied on all controller routes, it specifies the route path of the operation.

The optional `@api.middleware("three")` decorator on the route method allows you to specify addition middleware to implement within the route (you can apply this decorator multiple times per route to add additional middleware's).

The controllers middleware will run (in specified order) before the routes middleware is run (also in specified order)

The route verb (`get`,`put`,`post`,`delete` etc) is determined by the following rules:

1. If the route method is named exactly as a verb - that verb is used.
2. If you specify the optional `@api.verbs(...)` decorator - that verb (or those verbs) will be used.
3. if all else fails, `get`.

The route path is determined by combining the (optional) `routePrefix` from `@api.controller` with the `@api.route` decorator values

The optional `@api.contentType` decorator can be applied once on any controller routes, it specifies the content type of the request body (the default is `"application/json"`).

## Consumed Libraries

### [rokot-test](https://github.com/Rocketmakers/rokot-test)
The testing framework used within the Rokot Platform!

---
_Source: https://npm.io/package/rokot-apicontroller · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
