A simple, lightweight, robust and versatile framework for building REST Api services on top of Koa with the developer experience at heart.
MIT License
A simple, lightweight, robust and versatile framework for building REST Api services on top of Koa with the developer experience at heart.
The Koa-Restapi framework comes shipped with a built in json schema validator for validating http requests and service layer responses at runtime using AJV. Which is currently the fastest json schema validator.
By leveraging Typescripts abstract classes and generic types, it provides compile time type checking and auto generation of json schemas.
yarn add @ninsho/koa-restapi
Write an api endpoint class that extends the RestApiEndpoint abstract class.
Now create a resource service class that extends the ResourceService abstract class.
export class CreateUserApi extends RestApiEndpoint<CreateUser, User>{
public routePath: string = '/users';
public httpAction: HttpAction = HttpAction.POST;
constructor(service: CreateUserService) {
super(service, 'CreateUserApi');
}
}
export class CreateUserService extends ResourceService<Database, User>{
constructor(userService: Database) {
super(userService);
}
public async run(ctx: Context){
return await this.provider.createUser(ctx.params);
}
public async handleError(error: Error) {
const httpError = error as HttpError;
httpError.statusCode = 500;
return httpError;
}
}
Load the api middlware into a Koa application
import { getRouter } from '@ninsho/koa-restapi'
const provider = new Database();
const create_user_service = new CreateUserService(provider);
const create_user_api = new CreateUserApi(create_user_service);
app.use(bodyParser());
app.use(getRouter(create_user_api));
server = app.listen(3000);
Next create a .restapi.json
file in the same directory as the package.json
{
"include": "./users/api/*.ts", // api files
"models": "./users/model/models.ts", // model files
"outDir": "./" // output for the api.schema.json file
}
Finally parse the api file to determine the request and response types that the rest api is 'constrained' by and generate the json schemas for the validators
./package.json
"scripts": {
"parse": restapi
}
yarn parse
And thats all to it! The framework has created a request and response validator based on the types provided to the RestApiEndpoint class
ctx.params
after validation and responses are stored in ctx.state.response
after validation.
[
requestValidator,
.
. <-- custom middleware added here
resourceService,
responseHandler,
]
type Response = boolean