I am new to NestJs and new to nodejs as well. I am trying to implement the following but getting error.
I have few entities inside of an entity folder [see image]
I have one repository folder which is having one custom repository, organizationRepository.ts like following
import { OrganizationEntity } from 'src/entity/organization.entity';
import { Repository } from 'typeorm';
import { EntityRepository } from 'typeorm';
#EntityRepository(OrganizationEntity)
export class OrganizationRepository extends Repository<OrganizationEntity> {
findById(id: string): Promise<OrganizationEntity> {
return this.findOne(id);
}
}
and also having an repository.module.ts inside repository folder
import { Module } from '#nestjs/common';
import { OrganizationRepository } from './organizationRepository';
#Module({
exports: [OrganizationRepository],
providers: [OrganizationRepository],
})
export class RepositoryModule {}
I have one dao folder which is having one file OrganizationDao.ts like following
import { Inject, Injectable } from '#nestjs/common';
import { OrganizationEntity } from 'src/entity/organization.entity';
import { OrganizationRepository } from 'src/repository/organizationRepository';
#Injectable()
export class OrganizationDao {
constructor(private organizationRepository: OrganizationRepository) {}
findById(id: string): Promise<OrganizationEntity> {
return this.organizationRepository.findById(id);
}
}
and the following in dao.module.ts
import { Module } from '#nestjs/common';
import { RepositoryModule } from 'src/repository/repository.module';
import { OrganizationDao } from './OrganizationDao';
#Module({
imports: [RepositoryModule],
exports: [OrganizationDao],
providers: [OrganizationDao],
})
export class DaoModule {}
And finally one domain folder called organization which are 3 files - organization.controller.ts, organization.module.ts and organization.service.ts
service class is like following -
import { Inject, Injectable } from '#nestjs/common';
import { OrganizationDao } from 'src/dao/OrganizationDao';
#Injectable()
export class OrganizationService {
constructor(
#Inject('OrganizationDao')
private readonly organizationDao: OrganizationDao,
) {}
async findById(id: string): Promise<string> {
const org = await this.organizationDao.findById(id);
console.log('db : ' + JSON.stringify(org));
return `This action returns a organization`;
}
}
controller is like following -
import { Controller, Get, Param } from '#nestjs/common';
import { OrganizationService } from './organization.service';
#Controller('dev/api/')
export class OrganizationController {
constructor(private readonly organizationService: OrganizationService) {}
#Get('/organizations/:id')
findOne(#Param('id') id: string) {
return this.organizationService.findById(id);
}
}
and the organization.module be like following
import { Module } from '#nestjs/common';
import { OrganizationService } from './organization.service';
import { OrganizationController } from './organization.controller';
import { TypeOrmModule } from '#nestjs/typeorm';
import { OrganizationRepository } from 'src/repository/organizationRepository';
import { DaoModule } from 'src/dao/dao.module';
#Module({
imports: [TypeOrmModule.forFeature([OrganizationRepository]), DaoModule],
controllers: [OrganizationController],
providers: [OrganizationService],
})
export class OrganizationModule {}
and in app.module.ts is like following
import { Module } from '#nestjs/common';
import { TypeOrmModule } from '#nestjs/typeorm';
import { DaoModule } from './dao/dao.module';
import { OrganizationEntity } from './entity/organization.entity';
import { OrganizationModule } from './organization/organization.module';
import { RepositoryModule } from './repository/repository.module';
#Module({
imports: [
OrganizationModule,
DaoModule,
RepositoryModule,
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 9092,
username: 'dev',
password: 'dev',
database: 'dev',
entities: [OrganizationEntity],
synchronize: false,
}),
],
})
export class AppModule {}
Now when I am running the application, I am getting the following error:
internal/modules/cjs/loader.js:638
throw err;
^
Error: Cannot find module 'src/repository/repository.module'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (C:\Users\admin\Documents\my-first-nest-project\dist\src\dao\dao.module.js:12:29)
I cannot understand what I am doing wrong? Even if I make the RepositoryModule as Global() then also getting the same error at same line.
Related
I ran into a problem with NestJS dependencies, I just started learning Nest and still don't quite understand how to build the structure correctly.
Nest can't resolve dependencies of the ChatGateway (?). Please make sure that the argument ChatAuth at index [0] is available in the ChatGateway context.
My error in terminal
chat.module.ts
`
import { Module } from '#nestjs/common';
import { ChatAuth } from './chat.middlewares';
import { ChatGateway } from './chat.gateway';
import { AuthHelper } from '../auth/auth.helper';
import { JwtStrategy } from '../auth/auth.strategy';
#Module({
imports: [ChatGateway, ChatAuth],
controllers: [],
providers: [AuthHelper, JwtStrategy],
})
export class ChatModule {}
`
chat.gateway.ts
`
import {
SubscribeMessage,
WebSocketGateway,
OnGatewayInit,
WebSocketServer,
OnGatewayConnection,
OnGatewayDisconnect,
MessageBody,
} from '#nestjs/websockets';
import { Logger } from '#nestjs/common';
import { Socket, Server } from 'socket.io';
import { ChatAuth } from './chat.middlewares';
#WebSocketGateway(7000)
export class ChatGateway
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
#WebSocketServer() server: Server;
private chatAuthHelper: ChatAuth;
private logger: Logger = new Logger('ChatGateway');
constructor(chatAuthHelper: ChatAuth) {
this.chatAuthHelper = chatAuthHelper;
}
#SubscribeMessage('msgToServer')
handleMessage(client: Socket, payload: string): void {
console.log(payload);
this.server.emit('msgToClient', payload);
}
#SubscribeMessage('events')
handleEvent(#MessageBody() data: string): void {
const parsed = JSON.parse(JSON.stringify(data));
parsed.msg = parsed.msg + ' 3';
this.server.emit('onMessage', {
msg: 'New message',
content: parsed.msg,
});
}
afterInit(server: Server) {
this.logger.log('Init');
}
handleDisconnect(client: Socket) {
this.logger.log(`Client disconnected: ${client.id}`);
}
handleConnection(client: Socket, ...args: any[]) {
if (client.handshake.headers.authorization) {
const guard = this.chatAuthHelper.use(
client.handshake.headers.authorization,
);
}
this.logger.log(`Client connected: ${client.id}`);
}
}
`
chat.middlewares.ts
`
import { Injectable, NestMiddleware } from '#nestjs/common';
import { AuthHelper } from '../auth/auth.helper';
#Injectable()
export class ChatAuth implements NestMiddleware {
private helper: AuthHelper;
constructor(helper: AuthHelper) {
this.helper = helper;
}
public async use(token): Promise<object> {
const currentToken = token.split(' ')[1];
const user = await this.helper.validate(currentToken);
console.log(JSON.stringify(user));
return user;
}
}
`
app.module.ts
`
import { Module } from '#nestjs/common';
import * as path from 'path';
import { ConfigModule } from '#nestjs/config';
import { TypeOrmModule } from '#nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { getEnvPath } from './common/helper/env.helper';
import { TypeOrmConfigService } from './shared/typeorm/typeorm.service';
import { ApiModule } from './api/api.module';
import { ChatModule } from './api/chat/chat.module';
const getPathConfig: string = path.join(__dirname, '..', 'env');
const envFilePath: string = getEnvPath(getPathConfig);
#Module({
imports: [
ConfigModule.forRoot({ envFilePath, isGlobal: true }),
TypeOrmModule.forRootAsync({ useClass: TypeOrmConfigService }),
ApiModule,
ChatModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
`
Swapped ChatAuth / ChatModule imports
come on, read the docs :D
ChatAuth is not a module, then there's no reason it to be listed in the imports array.
the page https://docs.nestjs.com/websockets/gateways shows that the gateway should be in the providers array. Again, ChatGateway is not a module, then why did you put that into imports array? the docs are pretty clear on what is the role of each option of #Module({}).
Used "#nestjs/typeorm": "^9.0.1", "typeorm": "^0.3.9"
when using the withRepository method, an exception is thrown
ERROR [ExceptionsHandler] dataSource.createEntityManager is not a function
TypeError: dataSource.createEntityManager is not a function
import { Injectable } from "#nestjs/common";
import { DataSource } from "typeorm";
#Injectable()
export class BarService {
constructor(
private readonly barRepository: BarRepository,
private readonly dataSource: DataSource
) {}
async foo() {
await this.dataSource.manager.transaction((manager) => {
const barRepository = manager.withRepository(this.barRepository);
return;
});
}
}
import { Injectable } from '#nestjs/common';
import { DataSource, Repository } from 'typeorm';
import { BarEntity } from '../entities/bar.entity';
#Injectable()
export class BarRepository extends Repository<BarEntity> {
constructor(dataSource: DataSource) {
super(BarEntity, dataSource.createEntityManager());
}
}
import { Module } from '#nestjs/common';
import { TypeOrmModule } from '#nestjs/typeorm';
import { BarEntity } from './entities/bar.entity';
import { BarService } from './services/bar.service';
import { BarRepository } from './repositories/bar.repository';
#Module({
imports: [TypeOrmModule.forFeature([BarEntity])],
providers: [
BarService,
BarRepository
],
exports: [BarService],
})
export class BarModule {}
error at debbuger
I am getting the following error when trying to spin up nestjs
[Nest] 47548 - 04/23/2022, 10:41:12 AM ERROR [ExceptionHandler] Nest can't resolve dependencies of the HeicService (?, +). Please make sure that the argument dependency at index [0] is available in the HeicModule context.
Potential solutions:
- If dependency is a provider, is it part of the current HeicModule?
- If dependency is exported from a separate #Module, is that module imported within HeicModule?
#Module({
imports: [ /* the Module containing dependency */ ]
})
But as from my understanding I am doing everything right regards import/export of Modules, no circular dependency and so on. Here are my modules:
App
import { Module } from '#nestjs/common';
import { EurekaModule } from './eureka/eureka.module';
import { HeicModule } from './heic/heic.module';
#Module({
imports: [HeicModule, EurekaModule],
})
export class AppModule {}
Config
import { Module } from '#nestjs/common';
import { ConfigService } from './config.service';
#Module({
providers: [ConfigService],
exports: [ConfigService],
})
export class ConfigModule {}
ConfigService
import { Injectable } from '#nestjs/common';
import { Config } from './config.interface';
#Injectable()
export class ConfigService {
private readonly map: Config;
Redis
import { CacheModule, Module } from '#nestjs/common';
import { ClientsModule, Transport } from '#nestjs/microservices';
import { ConfigModule } from '../config/config.module';
import { ConfigService } from '../config/config.service';
import { RedisCacheService } from './redis-cache.service';
import * as redisStore from 'cache-manager-redis-store';
import { RedisPublishService } from './redis-publish.service';
#Module({
imports: [
CacheModule.register({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
store: redisStore,
host: configService.get('host'),
port: configService.get('port'),
keyPrefix: configService.get('keyPrefix'),
userName: configService.get('username'),
password: configService.get('password'),
ttl: configService.get('cacheTTL'),
}),
}),
ClientsModule.register([
{
name: 'PUBLISH_SERVICE',
transport: Transport.REDIS,
options: {
url: 'redis://localhost:6379',
},
},
]),
],
providers: [RedisCacheService, RedisPublishService],
exports: [RedisCacheService, RedisPublishService],
})
export class RedisModule {}
Redis Pub/Sub Service
import { Inject, Injectable } from '#nestjs/common';
import { ClientProxy } from '#nestjs/microservices';
import { ImageMessage } from './ImageMessage';
#Injectable()
export class RedisPublishService {
private readonly CHANNEL: string = 'heic-image-result';
constructor(#Inject('PUBLISH_SERVICE') private client: ClientProxy) {}
async publishMessage(imageMessage: ImageMessage) {
this.client.emit({ cmd: this.CHANNEL }, imageMessage);
}
}
Redis Cache Service
import { CACHE_MANAGER, Inject, Injectable } from '#nestjs/common';
import { Cache } from 'cache-manager';
import { ImageMessage } from './ImageMessage';
#Injectable()
export class RedisCacheService {
constructor(#Inject(CACHE_MANAGER) private readonly cache: Cache) {}
async get(key): Promise<ImageMessage> {
return this.cache.get(key);
}
async set(key, value) {
await this.cache.set(key, value, 120);
}
}
Heic
import { Module } from '#nestjs/common';
import { RedisModule } from '../redis/redis.module';
import { HeicService } from './heic.service';
import { MessageListenerController } from './message-listener.controller';
#Module({
imports: [RedisModule],
controllers: [MessageListenerController],
providers: [HeicService],
exports: [HeicService],
})
export class HeicModule {}
Service
import { Inject, Injectable } from '#nestjs/common';
import { ImageMessage } from '../redis/ImageMessage';
import { RedisCacheService } from '../redis/redis-cache.service';
import { RedisPublishService } from '../redis/redis-publish.service';
import { OutputFormatEnum } from './output-format.enum';
// eslint-disable-next-line #typescript-eslint/no-var-requires
const convert = require('heic-convert');
#Injectable()
export class HeicService {
constructor(
#Inject() private readonly redisPublishService: RedisPublishService,
#Inject() private readonly redisCache: RedisCacheService,
) {}
Anyone an idea what I am doing wrong?
You're using #Inject() in your constructors with no injection token. You should be passing the injection token you are wanting to inject here. The HeicService's constructor would then look something like this:
#Injectable()
export class HeicService {
constructor(
#Inject(RedisPublishService) private readonly redisPublishService: RedisPublishService,
#Inject(RedisCacheService) private readonly redisCache: RedisCacheService,
) {}
}
The other option, as you're already using classes for the RedisCacheService and RedisPublishService is to just remove the #Inject() decorators all togehter for the HeicService
However, I can't find any Repository.extend method in Repository class and there's nothing about it in the documentation. How to solve this?
typeorm version: "^0.3.0"
I'm using nest js and trying to create a custom repository.
First of all:
npm install #nestjs/typeorm#next
NOTE
In my project #nestjs/typeorm version is 9.0.0-next.2 and typeorm version is 0.3.6
Create a folder named database in the src of your project then create two files in (typeorm-ex.decorator.ts and typeorm-ex.module.ts)
// typeorm-ex.decorator.ts
import { SetMetadata } from "#nestjs/common";
export const TYPEORM_EX_CUSTOM_REPOSITORY = "TYPEORM_EX_CUSTOM_REPOSITORY";
export function CustomRepository(entity: Function): ClassDecorator {
return SetMetadata(TYPEORM_EX_CUSTOM_REPOSITORY, entity);
}
And next file
// typeorm-ex.module.ts
import { DynamicModule, Provider } from "#nestjs/common";
import { getDataSourceToken } from "#nestjs/typeorm";
import { DataSource } from "typeorm";
import { TYPEORM_EX_CUSTOM_REPOSITORY } from "./typeorm-ex.decorator";
export class TypeOrmExModule {
public static forCustomRepository<T extends new (...args: any[]) => any>(repositories: T[]): DynamicModule {
const providers: Provider[] = [];
for (const repository of repositories) {
const entity = Reflect.getMetadata(TYPEORM_EX_CUSTOM_REPOSITORY, repository);
if (!entity) {
continue;
}
providers.push({
inject: [getDataSourceToken()],
provide: repository,
useFactory: (dataSource: DataSource): typeof repository => {
const baseRepository = dataSource.getRepository<any>(entity);
return new repository(baseRepository.target, baseRepository.manager, baseRepository.queryRunner);
},
});
}
return {
exports: providers,
module: TypeOrmExModule,
providers,
};
}
}
Open your AppModule and modify it like the following:
#Module({
imports: [
TypeOrmModule.forRoot({
type: 'mssql',
...
entities: [Photo],
}),
TypeOrmExModule.forCustomRepository([PhotoRepository]),
...
],
controllers: [AppController],
providers: [
AppService
],
})
export class AppModule { }
You can create your customer repository like the following :
#CustomRepository(Photo)
export class PhotoRepository extends Repository<Photo> {
public async getAllPhoto() {
const query = this.createQueryBuilder('photo')
.where('photo.isPublished = :isPublished', { isPublished: true })
const photos = await query.getMany()
return photos
}
}
Everything works perfectly.
Thanks to #anchan828
In the new version of TypeORM (0.3.*), I am changing custom repositories to services.
Based on connection to multiple official documentation databases.
https://docs.nestjs.com/techniques/database#multiple-databases
Custom repository
#EntityRepository(Person)
export class PersonRepository extends Repository<Person> {...}
Custom repository as Service
#Injectable()
export class PersonRepository {
constructor(private dataSource: DataSource) { }
exampleQueryBuilder() {
return this.dataSource
.getRepository(Person)
.createQueryBuilder() ...
}
Repository injection
#Injectable()
export class PersonService {
constructor(
#Inject(PersonRepository)
private readonly personRepository: PersonRepository,
) {}
With the current version of TypeORM, it's possible to implement a custom repository in the following way utilizing DataSource.
// user.repository.ts
#Injectable()
export class UsersRepository extends Repository<UsersEntity> {
constructor(private dataSource: DataSource) {
super(UsersEntity, dataSource.createEntityManager());
}
async getById(id: string) {
return this.findOne({ where: { id } });
}
// ...
}
The repository is then injected into the service.
// user.service.ts
export class UserService {
constructor(private readonly userRepository: UserRepository) {}
async getById(id: string): Promise<User> {
return this.userRepository.getById(id);
}
// ...
}
and the module has imports for the feature and the repository as a provider.
// user.module.ts
#Module({
imports: [
TypeOrmModule.forFeature([UserEntity])],
// ...
],
providers: [UserService, UserRepository],
// ...
})
export class UserModule {}
The way I could solve this error is the following:
First, I created the file datasource.ts, I also declared the datasource, it follows the same structure as the ormconfig.js file:
import { DataSource } from 'typeorm';
require('dotenv').config();
export const AppDataSource = new DataSource({
type: 'mongodb',
url: process.env.MONGO_URI,
useNewUrlParser: true,
synchronize: true,
logging: true,
database: process.env.DB_DATABASE,
entities: ['dist/entities/*.js'],
useUnifiedTopology: true,
});
AppDataSource.initialize()
.then(() => {
console.log('Data Source has been initialized!');
})
.catch((err) => {
console.error('Error during Data Source initialization', err);
});
And, after that, I created a Custom Repository:
import { AppDataSource } from '#CustomDataSource';
import { Product } from '#Entities';
import { CreateProductDto, UpdateProductDto } from '#Products';
const dataSource = AppDataSource;
export const ProductRepository =
dataSource.getMongoRepository(Product).extend({
async findOneById(id: number): Promise<Product> {
const product = await ProductRepository.findOne({ where: { id }});
return product;
},
async findMany(): Promise<Product[]> {
const products = await ProductRepository.find();
return products;
},
});
In this way, you don't have to add the repositories in TypeORMModule.forFeature([]), for each module in which you are working.
Note that now, we don't call this, we call ProductRepository and the method directly.
As refer to the related PR, the migration is work in progress. You can checkout the latest progress by using:
yarn add #nestjs/typeorm#next
You can use custom dynamic module as a workaround, like this gist for now.
I created a utility method provideCustomRepository to simplify overriding a repository with nestjs / typeorm 0.3.x
https://gist.github.com/rhutchison/a530d89c37f1978a48dcee4bf2418cb7
import { Provider, Type } from '#nestjs/common';
import { getDataSourceToken, getRepositoryToken } from '#nestjs/typeorm';
import { DataSource, DataSourceOptions, Repository } from 'typeorm';
export function provideCustomRepository<T>(
entity: Type<T>,
repository: Type<Repository<T>>,
dataSource?: DataSource | DataSourceOptions | string
): Provider {
return {
provide: getRepositoryToken(entity),
inject: [getDataSourceToken(dataSource)],
useFactory(dataSource: DataSource) {
const baseRepository = dataSource.getRepository(entity);
return new repository(
baseRepository.target,
baseRepository.manager,
baseRepository.queryRunner
);
},
};
}
<script src="https://gist.github.com/rhutchison/a530d89c37f1978a48dcee4bf2418cb7.js"></script>
There is no need to create a separated repository file and the entity will be injected to the service just like that:
import { Injectable, NotFoundException } from '#nestjs/common';
import { Task } from './task.entity';
import { InjectRepository } from '#nestjs/typeorm';
import { Repository } from 'typeorm';
#Injectable()
export class TasksService {
constructor(
#InjectRepository(Task)
private taskRepository: Repository<Task>
) {}
async getTasksById(id: number): Promise<Task> {
const found = await this.taskRepository.findOne({ where: { id: id
}});
}
}
I hope this helps.
The process, that have worked for me:
a)Define your Entity: (task.entity.ts)
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
#Entity()
export class Task {
#PrimaryGeneratedColumn('uuid')
id: string;
#Column()
title: string;
}
b)Define your repository (tasks.repository.ts)
import { Injectable, NotFoundException } from '#nestjs/common';
import { DataSource, Repository } from 'typeorm';
import { Task } from './task.entity';
#Injectable()
export class TasksRepository extends Repository<Task> {
constructor(private dataSource: DataSource) {
super(Task, dataSource.createEntityManager());
}
async getById(id: string): Promise<Task> {
const found = await this.findOneBy({ id });
if (!found) {
throw new NotFoundException(`Task with ID "${id}" not found`);
}
return found;
}
}
c)Controller (tasks.controller.ts)
import {
Controller,
Get,
Param,
} from '#nestjs/common';
import { TasksService } from './tasks.service';
import { Task } from './task.entity';
#Controller('tasks')
export class TasksController {
constructor(private tasksService: TasksService) {}
#Get('/:id')
getTaskById(#Param('id') id: string): Promise<Task> {
return this.tasksService.getTaskById(id);
}
}
d)Define module (tasks.module.ts)
import { Module } from '#nestjs/common';
import { TypeOrmModule } from '#nestjs/typeorm';
import { Task } from './task.entity';
import { TasksController } from './tasks.controller';
import { TasksRepository } from './tasks.repository';
import { TasksService } from './tasks.service';
#Module({
imports: [TypeOrmModule.forFeature([Task])],
controllers: [TasksController],
providers: [TasksService, TasksRepository],
})
export class TasksModule {}
e)And in the root module (app.module.ts) - NOT FOR PRODUCTION
import { Module } from '#nestjs/common';
import { TasksModule } from './tasks/tasks.module';
import { TypeOrmModule } from '#nestjs/typeorm';
#Module({
imports: [
TasksModule,
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'postgres',
database: 'task-management',
autoLoadEntities: true,
synchronize: true,
}),
],
})
export class AppModule {}
Note: autoLoadEntities, loads automatically any entity defined. This must follow the name name_entity.entity.ts
Hope it helps
TypeORM CHANGELOG.md
In order to extend UserRepository functionality you can use .extend method of Repository class
Example
// user.repository.ts
export const UserRepository = dataSource.getRepository(User).extend({...})
Problem
NestJS with Typeorm dependancy error.
Description
When I insert #InjectRepository into my Session Repository class (session.repository.ts), the can't dependency errors occur. However, if I remove the #InjectRepository the error disappear and the application works fine.
Error
File: session.repository.ts
import { Injectable } from '#nestjs/common';
import { InjectRepository } from '#nestjs/typeorm';
import { Repository } from 'typeorm';
import { Session } from './session.entity';
#Injectable()
export class SessionRepository {
constructor(
// When I try to inject repository the error occur.
// When I remove the inject repository, no error occur.
#InjectRepository(Session)
private readonly session: Repository<Session>,
) {}
async test() {
return await this.session.find();
}
}
File: session.service.ts
import { Injectable } from '#nestjs/common';
import { ISessionConfig } from 'src/common/config/config.interface';
import { ConfigService } from 'src/common/config/config.service';
import { createHashedToken, getExpiresTime } from '../auth.helper';
import { SessionRepository } from './session.repository';
#Injectable()
export class SessionService {
private bytes: number;
private ttl: number;
constructor(
private readonly configService: ConfigService,
private readonly sessionRepository: SessionRepository,
) {
const sessionConfig = this.configService.get<ISessionConfig>('session');
this.bytes = sessionConfig.bytes;
this.ttl = sessionConfig.ttl;
}
getConfig(): ISessionConfig {
return { bytes: this.bytes, ttl: this.ttl };
}
async generateRefreshToken() {
const refreshToken = await createHashedToken(this.bytes);
const expires = getExpiresTime(this.ttl).toString();
return { refreshToken, expires };
}
}
File: session.module.ts
import { Module } from '#nestjs/common';
import { TypeOrmModule } from '#nestjs/typeorm';
import { Session } from './session.entity';
import { SessionRepository } from './session.repository';
import { SessionService } from './session.service';
#Module({
imports: [TypeOrmModule.forFeature([Session])],
providers: [SessionService, SessionRepository],
exports: [SessionService, SessionRepository],
})
export class SessionModule {}
File: auth.module.ts
import { Module } from '#nestjs/common';
import { AuthenticationModule } from './authentication/authentication.module';
import { JwtModule } from './jwt/jwt.module';
import { SessionModule } from './session/session.module';
#Module({
imports: [AuthenticationModule, JwtModule, SessionModule],
})
export class AuthModule {}
File: database.module.ts
import { Module } from '#nestjs/common';
import { TypeOrmModule, TypeOrmModuleOptions } from '#nestjs/typeorm';
import { IDatabaseConfig } from '../config/config.interface';
import { ConfigService } from '../config/config.service';
#Module({
imports: [
TypeOrmModule.forRootAsync({
inject: [ConfigService],
useFactory: (configService: ConfigService): TypeOrmModuleOptions => {
const dbConfig = configService.get<IDatabaseConfig>('database');
return {
type: 'mysql',
host: dbConfig.host,
port: dbConfig.port,
username: dbConfig.username,
password: dbConfig.password,
database: dbConfig.database,
entities: ['dist/**/*.entity{.ts,.js}'],
autoLoadEntities: true,
synchronize: true,
};
},
}),
],
})
export class DatabaseModule {}
File: app.module.ts
import { MiddlewareConsumer, Module, NestModule } from '#nestjs/common';
import { ConfigModule } from './common/config/config.module';
import { DatabaseModule } from './common/database/database.module';
import { HttpLoggerMiddleware } from './common/middlewares/http-logger.middleware';
import { AuthModule } from './modules/auth/auth.module';
import { PostsModule } from './modules/posts/posts.module';
import { UsersModule } from './modules/users/users.module';
#Module({
imports: [AuthModule, ConfigModule, DatabaseModule, PostsModule, UsersModule],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(HttpLoggerMiddleware).forRoutes('*');
}
}
I tried to solve the issue but, at the end, I am not able to solve it.
Please help me find the issue. Thank you.
Updated
I found out the problem, it is the naming issue. I changed the class name from SessionRepository -> SessionsRepository.