Giter Club home page Giter Club logo

nest-koa-adapter's Introduction

Nest Koa HTTP Adapter

This package allows to use Koa and Koa router together with Nest.js framework.

It consists of KoaAdapter which is basically just mapping between Nest server and Koa. NestKoaApplication is an interface of application created by NestFactory. NestKoaMiddleware and NestKoaFunctionalMiddleware are interfaces for writing middleware for Nest together with Koa. koaToNestMiddleware is an utility function which can convert your old Koa middleware so it can be used in Nest.

How to use

Create application

NestFactory.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));

Middleware

You can still use your old middleware by converting by using koaToNestMiddleware function.

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 NestKoaMiddleware interface.

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('*');
  }
}

CORS

To use CORS you'll have to install @koa/cors package.

npm install @koa/cors

After installation is done you can set CORS same way as in normal NEST application.

The enableCors method accepts options same as normal Nest application. The only difference is in origin property which should not be function.

const app = NestFactory.create<NestKoaApplication>(AppModule, new KoaAdapter());

app.enableCors({});

await app.init();

Static assets

To use static assets you have to install koa-static package.

npm install koa-static

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();

The useStaticAssets method also accepts options which are exactly same as those from koa-static.

Views engine

To use MVC pattern you'll have to install koa-views package. This package allows you to use your favourite templating system.

npm install koa-views

To setup the view engine you have to specify your views folder and other options from koa-views or consolidate which is used under the hood.

const app = NestFactory.create<NestKoaApplication>(AppModule, new KoaAdapter());

app.setViewEngine({
  viewsDir: path.join(__dirname, 'views'),
  map: {
    html: 'lodash',
  },
});

await app.init();

Caveats

Versioning feature is not yet supported.

Nest components which operates with Koa response like exception filters needs to use the koaReply utility function from this package because the implementation if the reply in adapter doesn't allow to use standard way of setting body and status properties.

Another option is to inject the HttpAdapterHost dependency and use reply reply method from httpAdapter object. But this is basically the same as using the koaReply.

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);
  }
}

nest-koa-adapter's People

Contributors

seidelmartin avatar tomastauer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

nest-koa-adapter's Issues

TypeError: applicationRef.isHeadersSent is not a function

"@nestjs/core": "^9.0.1",
"nest-koa-adapter": "^2.0.0",

Could u have a look at my problem?

TypeError: applicationRef.isHeadersSent is not a function
at ExceptionsHandler.catch (/Users/myname/Desktop/devRepository/fast-gateway/node_modules/@nestjs/core/exceptions/base-exception-filter.js:27:29)

I have some confusion, when i use nest/swagger it show the mix used of ts and js

I have some confusion, when I use nest/swagger it shows the mix used of ts and js. and there was not nest-koa-adapter/src folder, there was only nest-koa-adapter/dist

TypeError: res.type is not a function
    at /Users/hiretual/gitClone/bmc-v2/backend/node_modules/@nestjs/swagger/dist/swagger-module.js:45:17
    at /Users/hiretual/gitClone/bmc-v2/backend/node_modules/nest-koa-adapter/src/KoaAdapter.ts:146:7
    at /Users/hiretual/gitClone/bmc-v2/backend/node_modules/dd-trace/packages/datadog-instrumentations/src/koa.js:103:27
    at exports.AsyncResource.runInAsyncScope (async_hooks.js:197:9)
    at /Users/hiretual/gitClone/bmc-v2/backend/node_modules/dd-trace/packages/datadog-instrumentations/src/koa.js:92:31
    at /Users/hiretual/gitClone/bmc-v2/backend/node_modules/dd-trace/packages/datadog-shimmer/src/shimmer.js:22:21
    at dispatch (/Users/hiretual/gitClone/bmc-v2/backend/node_modules/koa-compose/index.js:42:32)
    at /Users/hiretual/gitClone/bmc-v2/backend/node_modules/koa-router/lib/router.js:372:16
    at dispatch (/Users/hiretual/gitClone/bmc-v2/backend/node_modules/koa-compose/index.js:42:32)
    at /Users/hiretual/gitClone/bmc-v2/backend/node_modules/koa-compose/index.js:34:12
    at dispatch (/Users/hiretual/gitClone/bmc-v2/backend/node_modules/koa-router/lib/router.js:377:31)
    at /Users/hiretual/gitClone/bmc-v2/backend/node_modules/dd-trace/packages/datadog-instrumentations/src/koa.js:103:27
    at exports.AsyncResource.runInAsyncScope (async_hooks.js:197:9)
    at /Users/hiretual/gitClone/bmc-v2/backend/node_modules/dd-trace/packages/datadog-instrumentations/src/koa.js:92:31
    at dispatch (/Users/hiretual/gitClone/bmc-v2/backend/node_modules/koa-compose/index.js:42:32)
    at /Users/hiretual/gitClone/bmc-v2/backend/node_modules/dd-trace/packages/datadog-instrumentations/src/koa.js:148:17

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.