@gabliam/koa
Version:
Gabliam plugin for add koa
50 lines (49 loc) • 1.95 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.UseKoaInterceptors = exports.toInterceptor = exports.isValidInterceptor = void 0;
const core_1 = require("@gabliam/core");
const web_core_1 = require("@gabliam/web-core");
/**
* Test if target is a valid interceptor
* @param target any
*/
const isValidInterceptor = (target) => {
const meta = Reflect.getOwnMetadata(web_core_1.METADATA_KEY.specialInterceptor, target.constructor || target);
return meta === undefined || meta === 'koa';
};
exports.isValidInterceptor = isValidInterceptor;
/**
* KoaInterceptor decorator
* class is an koa interceptor.
* Must return koaRouter middleware
*/
const KoaInterceptor = () => (target) => {
Reflect.defineMetadata(web_core_1.METADATA_KEY.specialInterceptor, 'koa', target);
};
/**
* Convert a Koa router middleware to a gabliam interceptor
*/
const toInterceptor = (mid) => {
const clazz = class {
async intercept(context, next) {
const ctx = context.state.context;
// eslint-disable-next-line @typescript-eslint/return-await
return await mid(ctx, next);
}
};
(0, web_core_1.Context)()(clazz.prototype, 'intercept', 0);
(0, web_core_1.Next)()(clazz.prototype, 'intercept', 1);
(0, core_1.Service)()(clazz);
KoaInterceptor()(clazz);
// metadata
Reflect.defineMetadata('design:type', Function, clazz.prototype, 'intercept');
Reflect.defineMetadata('design:paramtypes', [Function, Function], clazz.prototype, 'intercept');
Reflect.defineMetadata('design:returntype', Promise, clazz.prototype, 'intercept');
return clazz;
};
exports.toInterceptor = toInterceptor;
/**
* Alias for evict to use: UseInterceptors(toInterceptor(koaMid))
*/
const UseKoaInterceptors = (...mids) => (0, web_core_1.UseInterceptors)(...mids.map((m) => (0, exports.toInterceptor)(m)));
exports.UseKoaInterceptors = UseKoaInterceptors;