You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
44 lines
1.6 KiB
44 lines
1.6 KiB
import Controller from './Controller.ts'
|
|
import {Request} from './Request.ts'
|
|
import ResponseFactory from './response/ResponseFactory.ts'
|
|
import * as api from '../support/api.ts'
|
|
import JSONResponseFactory from './response/JSONResponseFactory.ts'
|
|
|
|
/**
|
|
* HTTP controller which wraps its handlers output in JSON response factories, if appropriate.
|
|
* @extends Controller
|
|
*/
|
|
export default class ApiController extends Controller {
|
|
public get_bound_method(method_name: string): (...args: any[]) => any {
|
|
// @ts-ignore
|
|
if ( typeof this[method_name] !== 'function' ) {
|
|
throw new TypeError(`Attempt to get bound method for non-function type: ${method_name}`)
|
|
}
|
|
|
|
return async (...args: any[]): Promise<any> => {
|
|
if ( args.length !== 1 ) {
|
|
// @ts-ignore
|
|
return this[method_name](...args)
|
|
}
|
|
|
|
const request: Request = args[0]
|
|
// @ts-ignore
|
|
const result = await this[method_name](request)
|
|
|
|
// If we have a request or a response factory, return that
|
|
if ( result instanceof Request || result instanceof ResponseFactory ) {
|
|
return result
|
|
}
|
|
|
|
// Otherwise, try to package the results as an API response
|
|
if ( Array.isArray(result) ) {
|
|
return this.make(JSONResponseFactory, api.many(result))
|
|
} else if ( typeof result === 'string' ) {
|
|
return this.make(JSONResponseFactory, api.message(result))
|
|
} else {
|
|
return this.make(JSONResponseFactory, api.one(result))
|
|
}
|
|
}
|
|
}
|
|
}
|