https://github.com/mhio/node-koa-api
Koa API generator
https://github.com/mhio/node-koa-api
Last synced: 3 months ago
JSON representation
Koa API generator
- Host: GitHub
- URL: https://github.com/mhio/node-koa-api
- Owner: mhio
- License: mit
- Created: 2020-08-13T03:20:39.000Z (almost 5 years ago)
- Default Branch: master
- Last Pushed: 2021-10-25T08:37:37.000Z (over 3 years ago)
- Last Synced: 2025-01-30T12:28:33.631Z (4 months ago)
- Language: JavaScript
- Size: 717 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- Changelog: Changelog.md
- License: LICENSE
Awesome Lists containing this project
README
@mhio/koa-api
--------------------A Koa API to do all the request heavy lifting, so you just write logic
Errors and json responses are handled, just `return` the data or `throw` the error
Based on [`@mhio/koa-api-handler`](https://github.com/mhio/node-koa-api-handle) and it's [message format](https://github.com/mhio/js-message)
## Install
```
yarn add @mhio/koa-api
npm install @mhio/koa-api
```## Usage
[API docs](doc/API.md)
```
const {KoaApi, KoaApiHandler} = require('@mhio/koa-api')class MyHandler extends KoaApiHandler {
static getWhatever(ctx) {
return 'whatever'
}
static createOveralls(ctx) {
const blah = { truth: false }
return blah
}
}const api = new KoaApi({ routes: MyHandler.routeConfig() })
api.listen().then(srv => console.log(srv))
``````
const {KoaApi} = require('@mhio/koa-api')class MyHandler {
static get error_message(){
return 'Failure'
}static async ok(ctx){
return {
ok: true,
request_id, ctx.state.request_id,
}
}static async other(){
return 'other'
}static async error(){
throw new Error(this.error_message)
}}
// Route config for the API
const routes = [
// Simple function
[ 'get', '/ok', MyHandler.ok ],// Function bound to parent
[ 'get', '/ok2', MyHandler, 'ok' ],// Object setup
{ method: 'post', path: '/other', fn: MyHandler.other },// binds `MyHandler` for you
{ method: 'get', path: '/error', handler_object: MyHandler, handler_function: 'error' },
]
const api = new KoaApi({ routes })
api.listen().then(srv => console.log(srv))
```