Our HTTP Framework for REST APIs

HTTP request mapping annotations for TypeScript in the same style as in Java's Spring @RequestMapping.

import Request, {
    GetMapping, 
    PostMapping, 
    RequestBody, 
    ResponseEntity, 
    RequestHeader, 
    RequestParam,
    Headers
} from "./fi/nor/ts/Request";

export interface ListDTO<T> {
    pageNumber: number;
    pageSize: number;
    content: Array<T>;
}

@RequestMapping("/foo/users")
@RequestMapping("/users")
export class UserController {
    private readonly _userService: UserService;

    constructor(userService: UserService) {
        this._userService = userService;
    }

    @GetMapping("/", "/list")
    public async getUserList(
        @RequestParam("p", Request.ParamType.INTEGER)
        pageNumber: number = 0,
        @RequestParam("l", Request.ParamType.INTEGER)
        pageSize: number = 10,
        @RequestHeader('accept', {defaultValue: '*/*'})
        accept: string
    ): Promise<ResponseEntity<ListDTO<UserModel>>> {

        // const parsedPageNumber = pageNumber ? parseInt(pageNumber, 10) : 0;
        // const parsedPageSize   = pageSize   ? parseInt(pageSize, 10)   : 10;

        return ResponseEntity.ok({
            pageNumber: pageNumber,
            pageSize: pageSize,
            content: await this._userService.getUserList(pageNumber, pageSize),
        });

    }

    @GetMapping("/items/{id}")
    public async getUserList(
        @PathVariable('id')
        id: string
    ): Promise<ResponseEntity<Json>> {

        return ResponseEntity.ok({
           itemId: id
        });

    }

    @PostMapping("/addUser")
    public async addUser (
        @RequestBody   user    : Json,
        @RequestHeader headers : Headers
    ) : Promise<ResponseEntity<Json>> {

        const host = headers.getHost();

        await this._userService.addUser(user);

        return ResponseEntity.ok({
            user: user,
            host: host
        });

    }

}

You can also use:

  • @Request.mapping instead of @RequestMapping,
  • @Request.param instead of @RequestParam,
  • @Request.header instead of @RequestHeader,
  • @Request.body instead of @RequestBody,
  • @Request.getMapping(...) instead of GetMapping(...) or Request.mapping(Request.Method.GET, ...)
  • @Request.putMapping(...) instead of PutMapping(...) or Request.mapping(Request.Method.PUT, ...)
  • @Request.postMapping(...) instead of PostMapping(...) or Request.mapping(Request.Method.POST, ...)
  • @Request.deleteMapping(...) instead of DeleteMapping(...) or Request.mapping(Request.Method.DELETE, ...)

For the actual server implementing REST API, see RequestServer.