在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:seidelmartin/nest-koa-adapter开源软件地址:https://github.com/seidelmartin/nest-koa-adapter开源编程语言:TypeScript 99.1%开源软件介绍:Nest Koa HTTP AdapterThis package allows to use Koa and Koa router together with Nest.js framework. It consists of How to useCreate applicationNestFactory.create<NestKoaApplication>(AppModule, new KoaAdapter());
// You can also pass your own instance of Koa app to the adapter
const koa = new Koa();
NestFactory.create<NestKoaApplication>(AppModule, new KoaAdapter(koa)); MiddlewareYou can still use your old middleware by converting by using const koaMiddleware = (ctx, next) => {
...
}
@Module({
controllers: [HelloWorldController],
})
class TestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(koaToNestMiddleware(koaMiddleware))
.forRoutes('*');
}
} Or you can implement class middleware by implementing class Middleware implements NestKoaMiddleware {
use(req: Koa.Request, res: Koa.Response, next: Koa.Next) {
...
}
}
@Module({
controllers: [HelloWorldController],
})
class TestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(Middleware)
.forRoutes('*');
}
} CORSTo use CORS you'll have to install
After installation is done you can set CORS same way as in normal NEST application.
const app = NestFactory.create<NestKoaApplication>(AppModule, new KoaAdapter());
app.enableCors({});
await app.init(); Static assetsTo use static assets you have to install
Once you have the dependency installed you can set you static assets folder. const app = NestFactory.create<NestKoaApplication>(AppModule, new KoaAdapter());
app.useStaticAssets(path.join(__dirname, 'static'));
// Or with options
app.useStaticAssets(path.join(__dirname, 'static'), options);
await app.init();
Views engineTo use MVC pattern you'll have to install
To setup the view engine you have to specify your views folder and other options from const app = NestFactory.create<NestKoaApplication>(AppModule, new KoaAdapter());
app.setViewEngine({
viewsDir: path.join(__dirname, 'views'),
map: {
html: 'lodash',
},
});
await app.init(); CaveatsNest components which operates with with Koa response like exception filters needs to use the Another option is to inject the Example@Catch()
export class ErrorFilter implements ExceptionFilter {
public catch(error: any, host: ArgumentsHost): void {
const httpArguments = host.switchToHttp().getResponse();
// Your exception handling logic
const reply = {};
const statusCode = 500;
koaReply(httpArguments.getResponse(), reply, statusCode);
}
} |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论