koa-hare v0.0.1
HareTS
Get started
HareTS can only be used on the typescript platform. It requires you to add decorators, which are only supported by typescript currently, to classes, methods, and fields, for implementing corresponding functions.
HareTS is a lightweight middleware of @types/koa
, providing RESTful router and validation of accepted fields. It's quite easy to set up just like other Koa middlewares as follows. Before listening to a port, you are required to scan files or directories to enable controllers.
// app.ts
import Koa = require('koa');
import { Hare } from 'koa-hare';
const app = new Koa();
const hare = new Hare();
// use middlewares
app.use(hare.middleware.bodyParser()); // optional middleware
app.use(hare.middleware.controller()); // core middleware
app.use(hare.middleware.response()); // optional middleware
// scan controller directory
hare.scanDir(path.join(__dirname, 'controller'));
app.listen(3000);
The following is a typical sample of a Hare controller. There is a mass of decorators imported from koa-hare
and been used. Each of them implements a specified function.
// controller/user.ts
import { Boolean, Controller, Email, File, Get, HareFile, Number, Optional, Post, Required } from 'koa-hare';
@Controller('user')
class User {
@Get('/:userId/name')
public async getUserName(
@Required() @Number() userId: number,
@Optional(true) @Boolean() isDeleted: boolean
): Promise<string> {
return `James Chan[${userId}]`;
}
@Post('/:id/email', { id: 'userId' })
public async updateEmail(
@Required() @Number() userId: number,
@Required() @Email() email: string
): Promise<string> {
return `Update email for user ${userId}: ${email}`;
}
@Post('/:id/avatar', { id: 'userId' })
public async updateAvatar(
@Required() @Number() userId: number,
@Required() @File() avatar: HareFile
): Promise<string> {
return `Update avatar for user ${userId}.\n` + `filepath: ${avatar.filepath}`;
}
}
@Controller()
- To declare a class as a controller class, and record a mapping string.@Get()
&@Post()
- To declare a method as a controller method, record a mapping string and an alias map. The controller method decorated by@Get()
will be matched up withGET
requests with specified URLs. The same for@Post()
and other similar decorators. TakegetUserName
for example, its full mapping string isuser/:id/name
, generated by concatenating the mapping string of its class and itself. Therefore, it would be matched by requests whose URL resembles it, for example,user/45/name
.@Required()
&@Optional()
- To determine whether a field is required. By default, every field is optional, unless it is decorated by@Required()
. If a field is required, Hare will throw an error if a certain request which doesn't provide it.@Optional()
accepts an optional parameter that acts as a default value.@Number()
,@Email()
&@File
- Validation rule for fields. Decorated by this series of decorators, a field will be validated according to the corresponding rules. User can also develop their own validation rule if necessary. Take@Number()
, Hare would throw aTypeError
if the provided value cannot be parsed to be a number.
Configuration
Set configurations when creating Hare instance. The following codes show the default value of configs.
import { Hare } from 'koa-hare';
const hare = new Hare({
// Whether enable debug mode.
debug: false,
// Whether validate for all controller methods.
// If disabled, Hare will only validate the controller method with Validate decorator.
autoValidate: true,
//Handler that handling error occurs in the process of validation.
validationErrorHandler: function(this: Hare, error: Error) {
if (this.getConfig('debug')) console.log(error);
},
// Handler that handling error occurs in the process of running controller method.
runningErrorHandler: function(this: Hare, error: Error) {
if (this.getConfig('debug')) console.log(error);
}
});
Decorators
The main idea of HareTS is to use decorators to set configurations. Decorators can be divided into the following types by modified object: class decorator
, method decorator
, and field decorator
.
Class decorators
@Controller(mappingString: string)
: To declare a class as a controller class, and record a mapping string.
Method decorators
@Validate()
: Controller methods decorated by@Validate()
will validate all fields accepted. IfautoValidate
is true (default), Hare will validate all methods even if the method isn't decorated by@Validate()
.
The following is a group of decorators who describe the expected HTTP method. Notice that multiple can be applied to one controller method.
@Get(mappingString: string, aliasMap: NodeJS.Dict<string> = null)
@Post(mappingString: string, aliasMap: NodeJS.Dict<string> = null)
@Put(mappingString: string, aliasMap: NodeJS.Dict<string> = null)
@Delete(mappingString: string, aliasMap: NodeJS.Dict<string> = null)
@Head(mappingString: string, aliasMap: NodeJS.Dict<string> = null)
@Connect(mappingString: string, aliasMap: NodeJS.Dict<string> = null)
@Options(mappingString: string, aliasMap: NodeJS.Dict<string> = null)
@Trace(mappingString: string, aliasMap: NodeJS.Dict<string> = null)
@Patch(mappingString: string, aliasMap: NodeJS.Dict<string> = null)
Field decorators
@Required()
@Optional(defaultValue: any = undefined)
@Number(regex: RegExp = undefined)
@String(regex: RegExp = undefined)
@Boolean()
@File()
@Email()
Middlewares
controller
It's the core middleware of Hare. It will parse requests and search for the matching controller method. If found, the method will be run. All the information of these processes will be stored in ctx.hare
, whose type is HareObject
. The HareObject
contains the following attributes.
matchSuccessfully
- Whether successfully matched.controllerClass
- Matched controller class.controllerInstance
- The instance of the matched controller.controllerMethod
- Matched controller method.urlArgs
- Arguments that are extracted from URL string.args
- All detected arguments from URL string, query string, HTTP request body, and file stream.files
- All files (binary stream) received.applyArgs
- Argument list that applied on controller method.validationPassed
- Whether validation passed.runSuccessfully
- With successfully matching, whether the controller method runs successfully and returns a proper result.returnValue
- The return value of the controller method (if runs successfully).errorInstance
- Instance of error encountered when running controller method. Be undefined if the controller method runs successfully.