Skip to content

Instantly share code, notes, and snippets.

@tzkmx
Last active January 20, 2023 01:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tzkmx/d586b62fa4ffa8379fe0f8785b28ad25 to your computer and use it in GitHub Desktop.
Save tzkmx/d586b62fa4ffa8379fe0f8785b28ad25 to your computer and use it in GitHub Desktop.
NestJS as sub app of express.js vanilla
{
"presets": [
["env", { "targets": {"node": "current" }, "debug": true }],
"stage-0"
],
"plugins": [
"transform-decorators-legacy",
"transform-runtime"
]
}
import express from 'express'
import bootstrapSubApp from './boot'
const app = express()
app.get('/', (req, res) => res.send('hello express'))
async function mountSubApp (app, mountPath, subAppBoot) {
const subApp = await subAppBoot()
await subApp.init()
app.use(mountPath, subApp.getHttpAdapter().getInstance())
return app
}
mountSubApp(app, '/onsub', bootstrapSubApp)
.then(app => app.listen(4000))
import { NestFactory } from '@nestjs/core'
import { SubAppModule } from './module'
async function bootstrap () {
const app = await NestFactory.create(SubAppModule)
return app
}
import { Controller, Dependencies, Get } from '@nestjs/common'
import { SubAppService } from './service'
@Controller('sub')
@Dependencies(SubAppService)
export class SubAppController {
constructor (appService) {
this.appService = appService
}
@Get()
getHello () {
return this.appService.getHello()
}
}
{
"compilerOptions": {
"target": "ES6",
"experimentalDecorators": true
},
"exclude": [
"node_modules"
]
}
import { Module } from '@nestjs/common'
import { SubAppController } from './controller'
import { SubAppService } from './service'
@Module({
imports: [],
controllers: [SubAppController],
providers: [SubAppService]
})
export class SubAppModule {}
{
"name": "express-with-nestjs-subapp",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "babel-node src/app.js",
"build": "babel src -d dist -s inline",
"build:run": "npm run build && node dist/app.js"
},
"license": "ISC",
"dependencies": {
"@nestjs/common": "^5.5.0",
"@nestjs/core": "^5.5.0",
"express": "^4.16.4",
"reflect-metadata": "^0.1.12",
"rxjs": "^6.3.3"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-plugin-external-helpers": "^6.22.0",
"babel-plugin-transform-decorators-legacy": "^1.3.5",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-stage-0": "^6.24.1"
}
}
import { Injectable } from '@nestjs/common'
@Injectable()
export class SubAppService {
getHello () {
return 'Hello from the Nest\n'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment