Fix for "Nest can't resolve dependencies of the MovieService." - nestjs

I keep getting this error but don't know why. If anyone could help me solve it, that would make my day 😁
Error: Nest can't resolve dependencies of the MovieService (?). Please make sure that the argument MovieRepository at index [0] is available in the MovieService context.
This is the structure of my MovieService:
import {Injectable} from "#nestjs/common";
import {InjectRepository} from "#nestjs/typeorm";
import {Repository} from "typeorm";
import {CreateMovieDto} from "./dto/create-movie.dto";
import {Movie} from "./movie.entity";
#Injectable()
export class MovieService {
constructor(
#InjectRepository(Movie)
private readonly movieRepository: Repository<Movie>
) {}
create(createMovieDto: CreateMovieDto): Promise<Movie> {
const movie = new Movie();
movie.path = createMovieDto.path;
movie.title = createMovieDto.title;
movie.originalTitle = createMovieDto.originalTitle;
movie.poster = createMovieDto.poster;
movie.descr = createMovieDto.descr;
movie.year = createMovieDto.year;
return this.movieRepository.save(movie);
}
async findAll(): Promise<Movie[]> {
return this.movieRepository.find();
}
findOne(id: string): Promise<Movie> {
return this.movieRepository.findOne(id);
}
findByPath(path: string): Promise<Movie> {
return this.movieRepository.findOne({path});
}
async remove(id: string): Promise<void> {
await this.movieRepository.delete(id);
}
}
The MovieModule :
import {Module} from "#nestjs/common";
import {TypeOrmModule} from "#nestjs/typeorm";
import {Movie} from "./movie.entity";
import {MovieService} from "./movie.service";
#Module({
imports: [TypeOrmModule.forFeature([Movie])],
providers: [MovieService],
exports: [MovieService],
})
export class MovieModule {}
The Movie entity :
import {Column, Entity, PrimaryGeneratedColumn} from "typeorm";
#Entity()
export class Movie {
#PrimaryGeneratedColumn()
id: number;
#Column()
path: string;
#Column()
title: string;
#Column()
originalTitle: string;
#Column()
poster: string;
#Column()
descr: string;
#Column()
year: string;
}
And the app module :
import {Module} from "#nestjs/common";
import {TypeOrmModule} from "#nestjs/typeorm";
import {AppController} from "./app.controller";
import {AppService} from "./app.service";
import {MovieModule} from "./movie/movie.module";
#Module({
imports: [
TypeOrmModule.forRoot({
type: "mysql",
host: "localhost",
port: 3306,
username: "*****",
password: "*****",
database: "*****",
autoLoadEntities: true,
synchronize: true,
}),
MovieModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
Edit 1
I tried copy-pasting the movie folder into a new nest project and it works. I'm even more confused on why I get this error
Here's my package.json
{
"name": "marineris",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"#nestjs/common": "^8.0.0",
"#nestjs/core": "^8.0.0",
"#nestjs/platform-express": "^8.0.0",
"#nestjs/typeorm": "^8.0.2",
"bcrypt": "^5.0.1",
"cookie-parser": "^1.4.5",
"hbs": "^4.1.2",
"mysql2": "^2.3.2",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0",
"sync-request": "^6.1.0",
"typeorm": "^0.2.38",
"uuidv4": "^6.2.12"
},
"devDependencies": {
"#nestjs/cli": "^8.0.0",
"#nestjs/schematics": "^8.0.0",
"#nestjs/testing": "^8.0.0",
"#types/cookie-parser": "^1.4.2",
"#types/express": "^4.17.13",
"#types/jest": "^27.0.1",
"#types/node": "^16.0.0",
"#types/supertest": "^2.0.11",
"#typescript-eslint/eslint-plugin": "^4.28.2",
"#typescript-eslint/parser": "^4.28.2",
"eslint": "^7.30.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.0",
"jest": "^27.0.6",
"prettier": "^2.3.2",
"supertest": "^6.1.3",
"ts-jest": "^27.0.3",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "^3.10.1",
"typescript": "^4.3.5"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

I solved my problem. I messed up my imports/exports in some of the files of the project and after double-checking them it worked.

Related

NestJS Graphql Fastify FastifyError: fastify-plugin: fastify-accepts - expected '3.x' fastify version, '4.6.0' is installed

I'm following the NestJS documentation on how to set up a fastify/apollo server with nest but after adding fastify to main.ts I get this error:
FastifyError: fastify-plugin: fastify-accepts - expected '3.x' fastify version, '4.6.0' is installed
I've tried installing fastify 3.x, changing versions of other modules but according to yarn.lock some modules need 3.x and others need 4.x.
These are the docs I'm following:
https://docs.nestjs.com/techniques/performance
https://docs.nestjs.com/graphql/quick-start
Here is my main.ts
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
import {
FastifyAdapter,
NestFastifyApplication,
} from '#nestjs/platform-fastify';
import { ValidationPipe } from '#nestjs/common';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({ logger: true }),
);
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();
Here is my package.json
{
"name": "app",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"#nestjs/apollo": "^10.1.0",
"#nestjs/common": "^9.0.0",
"#nestjs/core": "^9.0.0",
"#nestjs/graphql": "^10.1.2",
"#nestjs/platform-express": "^9.0.0",
"#nestjs/platform-fastify": "^9.1.1",
"apollo-server-fastify": "^3.10.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.13.2",
"firebase-admin": "^11.0.1",
"graphql": "^16.6.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0",
"ts-morph": "^16.0.0"
},
"devDependencies": {
"#nestjs/cli": "^9.0.0",
"#nestjs/schematics": "^9.0.0",
"#nestjs/testing": "^9.0.0",
"#types/express": "^4.17.13",
"#types/jest": "28.1.8",
"#types/node": "^16.0.0",
"#types/supertest": "^2.0.11",
"#typescript-eslint/eslint-plugin": "^5.0.0",
"#typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "28.1.3",
"prettier": "^2.3.2",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "28.0.8",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "4.1.0",
"typescript": "^4.7.4"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
#nestjs/common#^9 and #nestjs/platform-fastify#^9 require you to use fastify#^4. However, apllo-server-fastify does not support fastify#^4 and will not until apollo-server v4 comes out. Until then,. you can follow the docs and use mercurius instead.
Your other option would be to downgrade to #nestjs/common#^8 and #nestjs/platform-fastify#^8 along with #nestjs/graphql#^9 which supports fastify#^3

After installing NestJS 8.0.1 >> NestJS Error: Nest can't resolve dependencies of the (controller name)

full error:
ERROR [ExceptionHandler] Nest can't resolve dependencies of the CommitteesController (?).
Please make sure that the argument CommitteesService at index [0] is available in the CommitteesModule context.
Potential solutions:
- If CommitteesService is a provider, is it part of the current CommitteesModule?
- If CommitteesService is exported from a separate #Module, is that module imported within CommitteesModule?
#Module({
imports: [ /* the Module containing CommitteesService */ ]
})
at Injector.lookupComponentInParentModules (C:\Sites\AM-API-MDD\node_modules\#nestjs\core\injector\injector.js:193:19)
at async Injector.resolveComponentInstance (C:\Sites\AM-API-MDD\node_modules\#nestjs\core\injector\injector.js:149:33)
This was working with NestJS 7.6, but I upgraded the version to 8.0.1 and started getting this error.
There are several other modules that don't get an error, however, this is the first module in the list. The processor may not get to the other modules after returning this error.
committees.services.ts
import { Injectable } from '#nestjs/common';
import { PrismaService } from '../database';
import { defaultIncludeQuery, PER_PAGE_COUNT } from './constant';
import { Prisma } from '#prisma/client';
#Injectable()
export class CommitteesService {
constructor(private readonly prisma: PrismaService) {}
committees() {
return Promise.all([
this.prisma.committee.findMany({
include: {
PersonCommittee: {
include: {
Person: {
select: {
PKPersonID: true,
LastName: true,
FirstName: true,
MiddleName: true,
PreferredFirstName: true,
DisplayName: true,
EmploymentStatus: true
}
}
}
}
},
where: {
Active: true,
OR: [
{ PersonCommittee: { some: { Person: { EmploymentStatus: 'A' } } } },
{ PersonCommittee: { some: { Person: { EmploymentStatus: 'B' } } } },
{ PersonCommittee: { some: { Person: { EmploymentStatus: 'C' } } } },
],
}
})
])
}
committees.controller.ts
import {
Body,Controller,DefaultValuePipe,Delete,Get,Param,ParseIntPipe,Post,Put,Query,
} from '#nestjs/common';
import { CommitteesService } from './committees.service';
import { RESOURCE_BASE_ROUTE } from '../constant';
import { PER_PAGE_COUNT } from './constant';
import { Prisma } from '#prisma/client';
const Route = RESOURCE_BASE_ROUTE.committees;
#Controller()
export class CommitteesController {
constructor(private readonly committeesService: CommitteesService) {}
#Get(`${Route}`)
all() {
return this.committeesService.committees();
}
#Get(`${Route}/:id`)
byId(#Param('id', ParseIntPipe) id: number) {
if ( id == -1 ) {
return this.committeesService.committees()
}
return this.committeesService.committee({
CommitteeID: id,
});
}
committees.modules.ts
import { Module } from '#nestjs/common';
import { CommitteesController } from './committees.controller';
import { CommitteesService } from './Committees.service';
#Module({
imports: [],
controllers: [CommitteesController],
providers: [CommitteesService],
exports: [ CommitteesService],
})
export class CommitteesModule {}
package.json
{
"name": "am-api-mdd",
"version": "2.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"#angular/router": "^6.1.10",
"#nestjs/common": "^8.0.10",
"#nestjs/core": "^8.0.6",
"#nestjs/microservices": "^7.6.18",
"#nestjs/platform-express": "^7.6.18",
"node-windows": "^1.0.0-beta.5",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.6.7"
},
"devDependencies": {
"#nestjs/cli": "^8.1.2",
"#nestjs/schematics": "^7.3.1",
"#nestjs/testing": "^7.6.18",
"#prisma/client": "^3.1.1",
"#types/express": "^4.17.13",
"#types/jest": "^26.0.24",
"#types/node": "^14.17.7",
"#types/supertest": "^2.0.11",
"#typescript-eslint/eslint-plugin": "^4.29.0",
"#typescript-eslint/parser": "^4.29.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "7.2.0",
"eslint-plugin-prettier": "^3.4.0",
"jest": "^26.6.3",
"prettier": "^2.3.2",
"prisma": "^3.1.1",
"supertest": "^6.1.4",
"ts-jest": "^26.5.6",
"ts-loader": "^8.3.0",
"ts-node": "^9.0.0",
"tsconfig-paths": "^3.10.1",
"typescript": "^4.3.5"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

NestJs mongoose pre hooks not triggering

pre('save') and pre('remove') Hooks not triggering in nestjs.
I just started with nestjs. I've encountered an issue in which pre hooks are not working.
I followed official nestjs documentation for mongoose. but nothing works in my case
I want to update the product when review is created, deleted, and updated.
I want to inject productServiceinto hooks.
Below are the relevant snippets.
package.json
{
"name": "server",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"#nestjs/common": "^7.5.1",
"#nestjs/config": "^0.6.1",
"#nestjs/core": "^7.5.1",
"#nestjs/graphql": "^7.9.4",
"#nestjs/jwt": "^7.2.0",
"#nestjs/mongoose": "^7.2.4",
"#nestjs/passport": "^7.1.5",
"#nestjs/platform-express": "^7.5.1",
"#nestjs/serve-static": "^2.1.4",
"#types/bcrypt": "^3.0.0",
"apollo-server-express": "^2.19.1",
"bcrypt": "^5.0.0",
"class-transformer": "^0.3.2",
"class-validator": "^0.13.1",
"cloudinary": "^1.23.0",
"cookie-parser": "^1.4.5",
"graphql": "^15.4.0",
"graphql-tools": "^7.0.2",
"graphql-upload": "^11.0.0",
"mongoose": "^5.11.19",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.6.3",
"slugify": "^1.4.6",
"stripe": "^8.132.0"
},
"devDependencies": {
"#nestjs/cli": "^7.5.1",
"#nestjs/schematics": "^7.1.3",
"#nestjs/testing": "^7.5.1",
"#types/cookie-parser": "^1.4.2",
"#types/express": "^4.17.8",
"#types/jest": "^26.0.15",
"#types/node": "^14.14.6",
"#types/passport-jwt": "^3.0.3",
"#types/supertest": "^2.0.10",
"#typescript-eslint/eslint-plugin": "^4.6.1",
"#typescript-eslint/parser": "^4.6.1",
"eslint": "^7.12.1",
"eslint-config-prettier": "7.0.0",
"eslint-plugin-prettier": "^3.1.4",
"jest": "^26.6.3",
"prettier": "^2.1.2",
"supertest": "^6.0.0",
"ts-jest": "^26.4.3",
"ts-loader": "^8.0.8",
"ts-node": "^9.0.0",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.2.3"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
Review Module
#Module({
imports: [
forwardRef(() => ProductModule),
MongooseModule.forFeatureAsync([{
name: Review.name,
useFactory: (
) => {
const schema = ReviewSchema
schema.pre<ReviewDoc>('save', function (next) {
console.log("INSIDE SAVE")
next()
})
schema.pre<ReviewDoc>('remove', function (next) {
console.log("INSIDE REMOVE")
next()
})
return schema
}
}]),
MongooseModule.forFeature([{ name: Product.name, schema: ProductSchema }]),
MongooseModule.forFeature([{ name: Member.name, schema: MemberSchema }]),
MongooseModule.forFeature([{ name: Review.name, schema: ReviewSchema }])
],
providers: [ReviewService, ReviewResolver],
exports: [ReviewService]
})
export class ReviewModule { }
Review Entity
import { SchemaFactory, Schema, Prop } from "#nestjs/mongoose";
import * as mongoose from 'mongoose'
import { Member } from "../member/member.entity";
import { IReviewMember } from "./review.type";
export type ReviewDoc = Review & mongoose.Document
#Schema({ _id: false })
class ReviewMember {
#Prop({ type: mongoose.Schema.Types.ObjectId, ref: Member.name, required: true })
id: string;
#Prop({ required: true })
firstName: string;
#Prop({ required: true })
lastName: string;
#Prop({ type: String })
avatar?: string;
}
export const ReviewMemberSchema = SchemaFactory.createForClass(ReviewMember)
#Schema({
timestamps: true,
toJSON: {
transform: (doc, ret) => {
ret.id = doc._id;
delete ret._id
delete ret.__v
}
}
})
export class Review {
#Prop({ type: ReviewMemberSchema, required: true })
member: IReviewMember;
#Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'products', required: true })
productId: string;
#Prop()
productSlug: string;
#Prop()
comment: string;
#Prop({
set: function (rating: number) {
this._prevRating = this.rating;
return rating;
}
})
rating: number;
}
const ReviewSchema = SchemaFactory.createForClass(Review)
export { ReviewSchema }
Review Service
async createReview({ comment, member: user, productId, rating }: ICreateReview) {
const member = await this.members.findById(user.id)
if (!member) {
throw new NotFoundException(`no member found with member id "${productId}"`)
}
const product = await this.products.findById(productId)
if (!product) {
throw new NotFoundException(`no product found with product id "${productId}"`)
}
const review = await this.reviews.findOne({ "member.id": member.id, productId: product._id })
if (review) {
throw new ConflictException(`review already exist`)
}
// should trigger pre save but not working
const newReview = await this.reviews.create(
{
productId: product._id,
productSlug: product.slug,
member: {
firstName: member.firstName,
lastName: member.lastName,
avatar: member.avatar,
id: member._id
},
rating,
comment,
}
)
if (product.numOfReviews < 3) {
const { comment, member, rating, _id } = newReview
product.reviews.push({ comment, member, rating, id: _id })
await product.save()
}
return newReview;
}```

SyntaxError: Unexpected token { import {MigrationInterface, QueryRunner} from "typeorm"

I am recently working with NestJs and typeORM but am getting an error when I run my nest application. It generates this error
/home/backend/src/migrations/1611061187746-loadAllEntities.ts:1
import { MigrationInterface, QueryRunner } from 'typeorm';
^
SyntaxError: Unexpected token {
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
That error pointing at my generated migration ts file
//xxxxx-migration.ts
import {MigrationInterface, QueryRunner} from "typeorm";
export class migrationMessageDetail1611143681385 implements MigrationInterface {
name = 'migrationMessageDetail1611143681385'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query("CREATE TABLE `detail_pricing` (`id` int NOT NULL AUTO_INCREMENT, `dayStart` int NOT NULL, `dayEnd` int NOT NULL, `isCommonChoice` tinyint NOT NULL, `price` int NOT NULL DEFAULT '200', `pricePerday` int NOT NULL, `discount` int NOT NULL, `currency` varchar(255) NOT NULL, `withDeposit` int NOT NULL DEFAULT '30', `noDeposit` varchar(255) NOT NULL DEFAULT '56', `carId` int NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB");
....
Here is the ormconfig.ts file
//ormconfig.ts
import { ConnectionOptions } from 'typeorm';
const connectionOptions: ConnectionOptions = {
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: '',
database: 'cave',
synchronize: false,
migrationsRun: true,
logging: ['warn', 'error'],
entities: ['dist/src/domain/persistence/entities/**/*.js'],
migrationsTableName: 'migrations',
migrations: ['src/migrations/*.ts'],
subscribers: ['src/subscriber/**/*.ts'],
cli: {
entitiesDir: 'src/domain/persistence/entities',
migrationsDir: 'src/migrations',
subscribersDir: 'src/subscriber',
},
};
export default connectionOptions;
and here is my config tsconfig file
//tsconfig.json
{
"compilerOptions": {
"lib": [
"es5",
"es6",
"es2020",
"esnext"
],
"resolveJsonModule": true,
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2020",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"esModuleInterop": true
}
}
I have tried to
change migrations: ['src/migrations/*.ts'], to [__dirname + 'migrations/*{.ts/.js}'], in ormconfig.ts, no Error when running the App, but migration:run won't work..
Here how I run and generate migrations
#generate migration
$ ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js --config src/configs/ormconfig.ts migration:generate -n migrationMessageDetail -d src/migrations
#run migration
$ ./node_modules/.bin/ts-node ./node_modules/typeorm/cli.js --config src/configs/ormconfig.ts migration:run
here is my package json
{
"name": "cave-backend",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"#golevelup/nestjs-rabbitmq": "^1.15.2",
"#nestjs/common": "^7.5.5",
"#nestjs/config": "^0.6.1",
"#nestjs/core": "^7.5.5",
"#nestjs/mapped-types": "^0.1.1",
"#nestjs/passport": "^7.1.5",
"#nestjs/platform-express": "^7.5.5",
"#nestjs/platform-fastify": "^7.5.5",
"#nestjs/swagger": "^4.7.5",
"#nestjs/typeorm": "^7.1.5",
"#turf/distance": "^6.0.1",
"bcrypt": "^5.0.0",
"class-transformer": "^0.3.1",
"class-validator": "^0.12.2",
"dotenv": "^8.2.0",
"fastify-helmet": "^5.0.3",
"fastify-swagger": "^3.5.0",
"jwks-rsa": "^1.12.0",
"md5": "^2.3.0",
"mysql": "^2.18.1",
"nexmo": "^2.9.1",
"passport": "^0.4.1",
"passport-jwt": "^4.0.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.6.3",
"swagger-ui-express": "^4.1.5",
"typeorm": "^0.2.29",
"uuid": "^8.3.1"
},
"devDependencies": {
"#nestjs/cli": "^7.5.3",
"#nestjs/schematics": "^7.2.2",
"#nestjs/testing": "^7.5.5",
"#types/cache-manager": "^2.10.3",
"#types/express": "^4.17.9",
"#types/jest": "^26.0.15",
"#types/node": "^14.14.10",
"#types/supertest": "^2.0.10",
"#typescript-eslint/eslint-plugin": "^4.8.2",
"#typescript-eslint/parser": "^4.8.2",
"eslint": "^7.14.0",
"eslint-config-prettier": "^6.15.0",
"eslint-plugin-prettier": "^3.1.4",
"jest": "^26.6.3",
"prettier": "^2.2.1",
"supertest": "^6.0.1",
"ts-jest": "^26.4.4",
"ts-loader": "^8.0.11",
"ts-node": "^9.0.0",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.1.2"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
I could generate and run the migration but I don't know why this error SyntaxError: Unexpected token { import {MigrationInterface, QueryRunner} from "typeorm" occurs
Please help, Thank you so much
Have you tried to change this:
migrations: ['src/migrations/*.ts'],
to this:
migrations: ['src/migrations/*{.ts,.js}'],
?

Nest js packaging hangs at build process of the serverless framework

So i did a fresh install of nestjs application and i am trying to add the serverless framework with it.I also added few of the packages to support the serverless framework
{
"name": "n1",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"#hewmen/serverless-plugin-typescript": "^1.1.17",
"#nestjs/common": "^7.0.0",
"#nestjs/core": "^7.0.0",
"#nestjs/platform-express": "^7.0.0",
"aws-lambda": "^1.0.6",
"aws-serverless-express": "^3.3.8",
"express": "^4.17.1",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.5.4",
"serverless-offline": "^6.5.0",
"serverless-plugin-optimize": "^4.1.4-rc.1"
},
"devDependencies": {
"#nestjs/cli": "^7.0.0",
"#nestjs/schematics": "^7.0.0",
"#nestjs/testing": "^7.0.0",
"#types/express": "^4.17.3",
"#types/jest": "25.2.3",
"#types/node": "^13.9.1",
"#types/supertest": "^2.0.8",
"#typescript-eslint/eslint-plugin": "3.0.2",
"#typescript-eslint/parser": "3.0.2",
"eslint": "7.1.0",
"eslint-config-prettier": "^6.10.0",
"eslint-plugin-import": "^2.20.1",
"jest": "26.0.1",
"prettier": "^1.19.1",
"supertest": "^4.0.2",
"ts-jest": "26.1.0",
"ts-loader": "^6.2.1",
"ts-node": "^8.6.2",
"tsconfig-paths": "^3.9.0",
"typescript": "^3.7.4"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
and i have also added the serverless.yml file which is pointing in to lambda.handler
serverless.yml file
service:
name: nest-serverless-framework
plugins:
- '#hewmen/serverless-plugin-typescript'
- serverless-plugin-optimize
- serverless-offline
provider:
name: aws
runtime: nodejs12.x
functions:
main:
handler: src/lambda.handler
events:
- http:
method: any
path: /{any+}
So the handler file is simple it just exported a module that can bootstrap the application
import { Handler, Context } from 'aws-lambda';
import { Server } from 'http';
import { createServer, proxy } from 'aws-serverless-express';
import { eventContext } from 'aws-serverless-express/middleware';
import { NestFactory } from '#nestjs/core';
import { ExpressAdapter } from '#nestjs/platform-express';
import { AppModule } from './app.module';
import express from 'express';
const binaryMimeTypes: string[] = [];
let cachedServer: Server;
// Create the Nest.js server and convert it into an Express.js server
async function bootstrapServer(): Promise<Server> {
if (!cachedServer) {
const expressApp = express();
const nestApp = await NestFactory.create(AppModule, new
ExpressAdapter(expressApp))
nestApp.use(eventContext());
await nestApp.init();
cachedServer = createServer(expressApp, undefined,
binaryMimeTypes);
}
return cachedServer;
}
// Export the handler : the entry point of the Lambda function
export const handler: Handler = async (event: any, context: Context) => {
cachedServer = await bootstrapServer();
return proxy(cachedServer, event, context, 'PROMISE').promise;
}
but when i now try to do sls offline start, the computer just hangs and nothing happen and i have to restart the computer forcefully.
Any help would be appreciated.
I had a similar issue with v8 crashing during the serverless build. Changing packages from #hewmen/serverless-plugin-typescript to the original serverless-plugin-typescript fixed it.
Please note that aws-serverless-express says:
On 11/30 [2022], the AWS Serverless Express library is moving to Vendia and will be rebranded to serverless-express [...]
has become obsolete.
Probably the same job, you wanted to achieve, does the following Vendina example:
vendia serveless basic-starter-nestjs

Resources