Skip to content

Instantly share code, notes, and snippets.

@sonidelav
Created December 6, 2020 10:19
Show Gist options
  • Save sonidelav/91644ff05477ac7fd0de5686fe840536 to your computer and use it in GitHub Desktop.
Save sonidelav/91644ff05477ac7fd0de5686fe840536 to your computer and use it in GitHub Desktop.
NestJS as Nuxt's serverMiddleware (Nuxt Typescript)
import express from 'express';
import { NestFactory } from "@nestjs/core";
import { ExpressAdapter } from "@nestjs/platform-express";
import { ApiModule } from "./nest/ApiModule";
import { INestApplication, Injectable, NestMiddleware } from "@nestjs/common";
@Injectable()
export class AppMiddleware implements NestMiddleware {
private nestInstance: INestApplication | undefined;
constructor(private expressInstance: Express.Application) {
NestFactory
.create(ApiModule, new ExpressAdapter(expressInstance)).then(app => {
this.nestInstance = app;
this.nestInstance.init();
})
}
use(req: any, res: any, next: () => void) {
next();
}
}
const app = express();
const nestApp = new AppMiddleware(app);
app.use(nestApp.use);
export default {
path: '/api',
handler: app
};
import { Controller, Get } from "@nestjs/common";
@Controller()
export class ApiController {
@Get()
async root() {
return 'Hello World'
}
}
import { Module } from "@nestjs/common";
import { ApiController } from "./ApiController";
@Module({
controllers: [ApiController]
})
export class ApiModule {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment