How to use @nestjs/typeorm - 10 common examples

To help you get started, we’ve selected a few @nestjs/typeorm examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jmcdo29 / testing-nestjs / apps / typeorm-sample / src / cat / cat.service.spec.ts View on Github external
beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        CatService,
        {
          provide: getRepositoryToken(Cat),
          // define all the methods that you use from the catRepo
          // give proper return values as expected or mock implementations, your choice
          useValue: {
            find: jest.fn().mockResolvedValue(catArray),
            findOneOrFail: jest.fn().mockResolvedValue(oneCat),
            create: jest.fn().mockReturnValue(oneCat),
            save: jest.fn(),
            // as these do not actually use their return values in our sample
            // we just make sure that their resolee is true to not crash
            update: jest.fn().mockResolvedValue(true),
            // as these do not actually use their return values in our sample
            // we just make sure that their resolee is true to not crash
            delete: jest.fn().mockResolvedValue(true),
          },
        },
      ],
github mythal / boluo / server / src / app.module.ts View on Github external
host: POSTGRES_HOST,
    port: POSTGRES_PORT,
    username: POSTGRES_USERNAME,
    password: POSTGRES_PASSWORD,
    database: POSTGRES_DATABASE,
    entities: [__dirname + '/**/*.entity{.ts,.js}'],
    synchronize: true,
  }),
  GraphQLModule.forRoot({
    autoSchemaFile: '../schema.graphql',
    // GraphQL Subscriptions authentication https://github.com/nestjs/docs.nestjs.com/issues/394
    context: ({ req, connection }) => (connection ? { req: { headers: connection.context } } : { req }),
    installSubscriptionHandlers: true,
    debug: DEBUG,
  }),
  TypeOrmModule.forFeature([Message, User, Channel, Member, Invitation, Media]),
  JwtModule.register({
    secret: JWT_SECRET,
    signOptions: { expiresIn: JWT_EXPIRES_IN },
  }),
];

if (DEBUG) {
  const rootPath = join(__dirname, '../../web/dist');
  imports.unshift(ServeStaticModule.forRoot({ rootPath }));
}

@Module({
  imports,
  controllers: [MediaController],
  providers: [
    DateScalar,
github mythal / boluo / server / src / app.module.ts View on Github external
import { Invitation } from './invitaions/invitaions.entity';
import { MemberService } from './members/members.service';
import { RedisService } from './redis/redis.service';
import { DateScalar } from './scalars';
import { ChannelEventResolver } from './events/events.resolver';
import { EventService } from './events/events.service';
import { MediaService } from './media/media.service';
import { MediaResolver } from './media/media.resolver';
import { Media } from './media/media.entity';
import { MediaController } from './media/media.controller';
import { AuthResolver } from './auth/auth.resolver';
import { RandomService } from './random/random.service';

const imports = [
  PassportModule.register({ defaultStrategy: 'jwt' }),
  TypeOrmModule.forRoot({
    type: 'postgres',
    host: POSTGRES_HOST,
    port: POSTGRES_PORT,
    username: POSTGRES_USERNAME,
    password: POSTGRES_PASSWORD,
    database: POSTGRES_DATABASE,
    entities: [__dirname + '/**/*.entity{.ts,.js}'],
    synchronize: true,
  }),
  GraphQLModule.forRoot({
    autoSchemaFile: '../schema.graphql',
    // GraphQL Subscriptions authentication https://github.com/nestjs/docs.nestjs.com/issues/394
    context: ({ req, connection }) => (connection ? { req: { headers: connection.context } } : { req }),
    installSubscriptionHandlers: true,
    debug: DEBUG,
  }),
github FunnyLiu / nestDemo / serve-data / src / app.module.ts View on Github external
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Connection } from 'typeorm';
import { ProductModule } from './product/product.module';
import { HealthModule } from './health/health.module';
import { LoggerModule } from './logger/logger.module';
import { RedisModule } from './redis/redis.module';
import { ElasticSearchModule } from './elasticsearch/elasticsearch.module';
import { UserModule } from './user/user.module';
import { ConfigModule } from './config/config.module';
import { ConfigService } from './config/config.service';

@Module({
  imports: [
    TypeOrmModule.forRoot(),
    HealthModule,
    ConfigModule,
    // RedisModule,
    // ElasticSearchModule.registerAsync({
    //   imports:[ConfigModule],
    //   useFactory:async (ConfigService:ConfigService)=>(ConfigService.getESConfig()),
    //   inject:[ConfigService]
    // }), 
    LoggerModule,
    UserModule,
    ProductModule
  ],
  controllers: [
    AppController 
  ],
  providers: []
github jo0ger / node-server / src / app.module.ts View on Github external
import { ArticleModule } from './modules/article/article.module'
import { TypeormService } from './config/typeorm/typeorm.service'
import { TypeormModule } from './config/typeorm/typeorm.module'
import { VarModule } from './config/var/var.module'
import { LoggerModule } from './shared/logger/logger.module'
import { GraphQLModule } from '@nestjs/graphql'
import { GraphqlService } from './config/graphql/graphql.service'
import { CategoryModule } from './modules/category/category.module';

@Module({
  imports: [
    VarModule,
    ArticleModule,
    LoggerModule,
    TypeormModule,
    TypeOrmModule.forRootAsync({
      // TIP: Here need to import the VarModule for using VarService
      imports: [VarModule],
      useClass: TypeormService
    }),
    GraphQLModule.forRootAsync({
      imports: [VarModule, LoggerModule],
      useClass: GraphqlService
    }),
    CategoryModule
  ],
  controllers: [AppController],
  providers: [AppService, TypeormService]
})
export class AppModule {}
github saltyshiomix / ark / server / logics / logic.module.ts View on Github external
import {
  Module,
  INestApplication,
} from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { TypeOrmService } from './database/typeorm.service';
import { EnvModule } from './env/env.module';
import { SessionModule } from './session/session.module';
import { AuthModule } from './auth/auth.module';
import { UserModule } from './user/user.module';

@Module({
  imports: [
    TypeOrmModule.forRootAsync({
      imports: [EnvModule],
      useClass: TypeOrmService,
    }),
    EnvModule,
    SessionModule,
    AuthModule,
    UserModule,
  ],
})
export class LogicModule {
  public initialize(app: INestApplication) {
    // enable session store in PostgreSQL
    app.get(SessionModule).initialize(app);

    // enable passport session
    // NOTE: we must use this at the end of `app.use()` list
github vendure-ecommerce / vendure / packages / core / src / service / service.module.ts View on Github external
static forWorker(): DynamicModule {
        if (!workerTypeOrmModule) {
            workerTypeOrmModule = TypeOrmModule.forRootAsync({
                imports: [ConfigModule],
                useFactory: (configService: ConfigService) => {
                    const { dbConnectionOptions, workerOptions } = configService;
                    if (workerOptions.runInMainProcess) {
                        // When running in the main process, we can re-use the existing
                        // default connection.
                        return {
                            ...dbConnectionOptions,
                            name: 'default',
                            keepConnectionAlive: true,
                        };
                    } else {
                        return {
                            ...dbConnectionOptions,
                        };
                    }
github CatsMiaow / node-nestjs-structure / src / app.module.ts View on Github external
import { AuthenticatedGuard } from './common/guards';
import { LoggerMiddleware } from './common/middleware';
import { configuration } from './config';
import { SampleModule } from './sample/sample.module';

@Module({
  imports: [
    // Configuration
    // https://docs.nestjs.com/techniques/configuration
    ConfigModule.forRoot({
      isGlobal: true,
      load: [configuration]
    }),
    // Database
    // https://docs.nestjs.com/techniques/database
    TypeOrmModule.forRootAsync({
      useFactory: async (config: ConfigService) => ({
        entities: [`${__dirname}/entity/**/*.{js,ts}`],
        subscribers: [`${__dirname}/subscriber/**/*.{js,ts}`],
        migrations: [`${__dirname}/migration/**/*.{js,ts}`],
        ...config.get('db')
      }),
      inject: [ConfigService]
    }),
    // Static Folder
    // https://docs.nestjs.com/recipes/serve-static
    // https://docs.nestjs.com/techniques/mvc
    ServeStaticModule.forRoot({
      rootPath: `${__dirname}/../public`,
      renderPath: '/'
    }),
    // Module Router
github xmlking / ngx-starter-kit / apps / api / src / app / core / core.module.ts View on Github external
return rc
    .keys()
    .filter(filePath => !filePath.includes('base'))
    .flatMap(key => Object.values(rc(key)))
    .filter(isClass);
}

const requireContext = (require as any).context('../..', true, /\.entity.ts/);
// const requireContext = (require as any).context('../..', true, /^\.\/.*\/.*\/(?!(base|audit-base)).*\.entity.ts$/);
const entities = requireAllClasses(requireContext);

@Module({
  imports: [
    ConfigModule,
    EmailModule.forRoot(env.email),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (config: ConfigService) =>
        ({
          ...env.database,
          entities,
        } as ConnectionOptions),
      inject: [ConfigService],
    }),
  ],
  controllers: [],
  providers: [
    // Enable for debugging in Dev env.
    // {
    //   provide: APP_INTERCEPTOR,
    //   useClass: LoggingInterceptor,
    // },
github notadd / nt-module-user / test / user-module / app.module.ts View on Github external
import { Inject, Module, OnModuleInit } from '@nestjs/common';
import { ModulesContainer } from '@nestjs/core/injector/modules-container';
import { MetadataScanner } from '@nestjs/core/metadata-scanner';
import { InjectRepository, TypeOrmModule } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { PERMISSION_DEFINITION } from './decorators/permission.decorator.test';
import { RESOURCE_DEFINITION } from './decorators/resource.decorator.test';
import { Permission } from './entities/permission.entity';
import { Resource } from './entities/resource.entity';
import { UserModule } from './modules/user.module';

@Module({
    imports: [
        TypeOrmModule.forFeature([Resource, Permission]),
        TypeOrmModule.forRoot({
            type: 'postgres',
            host: 'localhost',
            port: 5432,
            username: 'postgres',
            password: '123456',
            database: 'postgres',
            entities: [__dirname + '/./*/*.entity.ts'],
            synchronize: true,
            dropSchema: true,
            logging: true
        }),
        UserModule
    ]
})
export class AppModule implements OnModuleInit {
    private readonly metadataScanner: MetadataScanner;