@nestjs/common#Type TypeScript Examples

The following examples show how to use @nestjs/common#Type. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: app.utils.ts    From nest-js-boilerplate with MIT License 7 votes vote down vote up
DtoFactory = {
  wrap<T>(responseDto: T): Type<unknown> {
    class SuccessResponseDto {
      @ApiProperty({ type: String })
      public message: string = '';

      @ApiProperty({ type: responseDto })
      public data: T | null = null;
    }

    return SuccessResponseDto;
  },
}
Example #2
Source File: subscriber.ts    From pebula-node with MIT License 6 votes vote down vote up
export function SbIntercept(...interceptors: Array<SbInterceptor | Type<SbInterceptor>>) {
  return <T extends Record<K, OperatorFunction<SbContext, any>>, K extends string>(target: T, key: K): void => {
    const ctrlInterceptors: SbInterceptorMetadataForTarget
      = Reflect.getMetadata(SERVICE_BUS_INTERCEPTORS_METADATA, target) || new Map<string | symbol, Array<SbInterceptor | Type<SbInterceptor>>>();

    if (ctrlInterceptors.size === 0) {
      Reflect.defineMetadata(SERVICE_BUS_INTERCEPTORS_METADATA, ctrlInterceptors, target);
    }

    if (!ctrlInterceptors.has(key)) {
      ctrlInterceptors.set(key, []);
    }
    ctrlInterceptors.get(key).push(...interceptors);
  };
}
Example #3
Source File: paged-list.dto.ts    From codeclannigeria-backend with MIT License 6 votes vote down vote up
export function PagedListDto<T extends ClassType>(
  entityDto: T
): Type<IPagedListDto<T>> {
  class Paged implements IPagedListDto<T> {
    totalCount: number;
    @ApiProperty({ type: entityDto, isArray: true })
    items: T[];
  }

  return Paged;
}
Example #4
Source File: data.factory.ts    From nestjs-seeder with MIT License 6 votes vote down vote up
static createForClass(target: Type<unknown>): Factory {
    if (!target) {
      throw new Error(
        `Target class "${target}" passed in to the "TemplateFactory#createForClass()" method is "undefined".`,
      );
    }

    const properties = FactoryMetadataStorage.getPropertyMetadatasByTarget(
      target,
    );

    return {
      generate: (count: number, values: Record<string, any> = {}): Record<string, FactoryValue>[] => {
        const ret = Array<Record<string, FactoryValue>>();
        for (let i = 0; i < count; i++) {
          ret.push(this.generate(properties, values));
        }
        return ret;
      },
    };
  }
Example #5
Source File: bull.module.ts    From nestjs-bullmq with MIT License 6 votes vote down vote up
private static createAsyncProviders(
    options: BullModuleAsyncOptions,
  ): Provider[] {
    const optionalSharedConfigHolder = createConditionalDepHolder(
      getSharedConfigToken(options.configKey),
    );

    if (options.useExisting || options.useFactory) {
      return [
        optionalSharedConfigHolder,
        this.createAsyncOptionsProvider(options, optionalSharedConfigHolder),
      ];
    }
    if (!options.useClass) {
      // fallback to the "registerQueue" in case someone accidentally used the "registerQueueAsync" instead
      return createQueueOptionProviders([options]);
    }
    const useClass = options.useClass as Type<BullOptionsFactory>;
    return [
      optionalSharedConfigHolder,
      this.createAsyncOptionsProvider(options, optionalSharedConfigHolder),
      {
        provide: useClass,
        useClass,
      },
    ];
  }
Example #6
Source File: dynamoose-core.module.ts    From nestjs-dynamoose with MIT License 6 votes vote down vote up
private static createAsyncProviders(
    options: DynamooseModuleAsyncOptions,
  ): Provider[] {
    if (options.useExisting || options.useFactory) {
      return [this.createAsyncOptionsProvider(options)];
    }
    const useClass = options.useClass as Type<DynamooseOptionsFactory>;
    return [
      this.createAsyncOptionsProvider(options),
      {
        provide: useClass,
        useClass,
      },
    ];
  }
Example #7
Source File: mikro-orm.providers.ts    From nestjs with MIT License 6 votes vote down vote up
export function createEntityManagerProvider(
  scope = Scope.DEFAULT,
  entityManager: Type = EntityManager,
  contextName?: string,
): Provider<EntityManager> {
  return {
    provide: contextName ? getEntityManagerToken(contextName) : entityManager,
    scope,
    useFactory: (orm: MikroORM) => scope === Scope.DEFAULT ? orm.em : orm.em.fork(),
    inject: [contextName ? getMikroORMToken(contextName) : MikroORM],
  };
}
Example #8
Source File: pact-provider-core.module.ts    From nestjs-pact with MIT License 6 votes vote down vote up
private static createAsyncOptionsProvider(options: PactProviderModuleAsyncOptions): Provider {
    if (options.useFactory) {
      return {
        inject: options.inject || [],
        provide: PactModuleProviders.ProviderOptions,
        useFactory: options.useFactory,
      };
    }

    const inject = [(options.useClass || options.useExisting) as Type<PactProviderOptionsFactory>];

    return {
      provide: PactModuleProviders.ProviderOptions,
      useFactory: async (optionsFactory: PactProviderOptionsFactory) =>
        await optionsFactory.createPactProviderOptions(),
      inject,
    };
  }
Example #9
Source File: gcloud-stroage-file.interceptor.ts    From nestjs-gcloud-storage with MIT License 6 votes vote down vote up
export function GCloudStorageFileInterceptor(
  fieldName: string,
  localOptions?: MulterOptions,
  gcloudStorageOptions?: Partial<GCloudStoragePerRequestOptions>,
): Type<NestInterceptor> {
  @Injectable()
  class MixinInterceptor implements NestInterceptor {
    public interceptor: NestInterceptor;

    constructor(private readonly gcloudStorage: GCloudStorageService) {
      this.interceptor = new (FileInterceptor(fieldName, localOptions))();
    }

    async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
      (await this.interceptor.intercept(context, next)) as Observable<any>;

      const request = context.switchToHttp().getRequest();
      const file = request[fieldName];

      if (!file) {
        Logger.error(
          'GCloudStorageFileInterceptor',
          `Can not intercept field "${fieldName}". Did you specify the correct field name in @GCloudStorageFileInterceptor('${fieldName}')?`,
        );
        return;
      }

      const storageUrl = await this.gcloudStorage.upload(file, gcloudStorageOptions);
      file.storageUrl = storageUrl;
      return next.handle();
    }
  }

  const Interceptor = mixin(MixinInterceptor);
  return Interceptor as Type<NestInterceptor>;
}
Example #10
Source File: service-bus.module.ts    From pebula-node with MIT License 6 votes vote down vote up
function normalizeProvider(provider: Omit<Exclude<Provider, Type<any>>, 'provide'> | Type<any>): Provider {
  if (typeof provider === 'function') {
    provider = { useClass: provider };
  }
  return {
    ...(provider as Exclude<Provider, Type<any>>),
    provide: SB_META_HELPER_FACTORY_TOKEN,
  };
}
Example #11
Source File: module.ts    From nest-notifications with MIT License 6 votes vote down vote up
private static createStorageOptionsProvider(
    options: NotificationAsyncOptions,
  ): Provider {
    if (options.useFactory) {
      return {
        provide: NOTIFICATION_OPTIONS,
        useFactory: options.useFactory,
        inject: options.inject || [],
      };
    }

    const inject = [
      (options.useClass || options.useExisting) as Type<NotificationOptions>,
    ];

    return {
      provide: NOTIFICATION_OPTIONS,
      useFactory: async (optionsFactory: NotificationAsyncOptionsFactory) =>
        await optionsFactory.createNotificationOptions(),
      inject,
    };
  }
Example #12
Source File: sqs.module.ts    From nestjs-sqs with MIT License 6 votes vote down vote up
private static createAsyncProviders(options: SqsModuleAsyncOptions): Provider[] {
    if (options.useExisting || options.useFactory) {
      return [this.createAsyncOptionsProvider(options)];
    }
    const useClass = options.useClass as Type<SqsModuleOptionsFactory>;
    return [
      this.createAsyncOptionsProvider(options),
      {
        provide: useClass,
        useClass,
      },
    ];
  }
Example #13
Source File: strategy.explorer.ts    From nestjs-oauth2-server-module with MIT License 6 votes vote down vote up
flatMap<T>(
        modules: Module[],
        callback: (instance: InstanceWrapper) => Type<any> | undefined,
    ): Type<T>[] {
        const items = modules
            .map(module => [...module.providers.values()].map(callback))
            .reduce((a, b) => a.concat(b), []);
        return items.filter(element => !!element) as Type<T>[];
    }
Example #14
Source File: queue.module.ts    From nest-amqp with MIT License 6 votes vote down vote up
private static createAsyncProviders(options: QueueModuleAsyncOptions): Provider[] {
    if (!options.useClass && !options.useExisting && !options.useFactory) {
      throw new Error('Must provide factory, class or existing provider');
    }

    if (options.useExisting || options.useFactory) {
      return [this.createAsyncQueueModuleOptionsProvider(options), this.createAsyncAMQConnectionsOptionsProvider(options)];
    }

    const useClass = options.useClass as Type<QueueModuleOptionsFactory>;

    return [
      this.createAsyncQueueModuleOptionsProvider(options),
      this.createAsyncAMQConnectionsOptionsProvider(options),
      {
        provide: useClass,
        useClass,
      },
    ];
  }
Example #15
Source File: pdf.module.ts    From nestjs-pdf with MIT License 6 votes vote down vote up
static createAsyncProviders(
        options: PDFModuleRegisterAsyncOptions,
    ): Provider[] {
        if (options.useFactory || options.useExisting) {
            return [PDFModule.createAsyncOptionsProvider(options)];
        }

        const useClass = options.useClass as Type<PDFOptionsFactory>;
        return [
            PDFModule.createAsyncOptionsProvider(options),
            {
                provide: useClass,
                useClass,
            },
        ];
    }
Example #16
Source File: gcloud-storage-files.interceptor.ts    From nestjs-gcloud-storage with MIT License 6 votes vote down vote up
export function GCloudStorageFilesInterceptor(
  fieldName: string,
  localOptions?: MulterOptions,
  gcloudStorageOptions?: Partial<GCloudStoragePerRequestOptions>,
): Type<NestInterceptor> {
  @Injectable()
  class MixinInterceptor implements NestInterceptor {
    public interceptor: NestInterceptor;

    constructor(private readonly gcloudStorage: GCloudStorageService) {
      this.interceptor = new (FilesInterceptor(fieldName, 20, localOptions))();
    }

    async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
      (await this.interceptor.intercept(context, next)) as Observable<any>;

      const request = context.switchToHttp().getRequest();

      const files = request[fieldName];

      if (!files.length) {
        Logger.error(
          'GCloudStorageFilesInterceptor',
          `Can not intercept field "${fieldName}". Did you specify the correct field name in @GCloudStorageFilesInterceptor('${fieldName}')?`,
        );
        return;
      }

      for (const file of files) file.storageUrl = await this.gcloudStorage.upload(file, gcloudStorageOptions);

      return next.handle();
    }
  }

  const Interceptor = mixin(MixinInterceptor);
  return Interceptor as Type<NestInterceptor>;
}
Example #17
Source File: gql-execution-context.ts    From nestjs-mercurius with MIT License 6 votes vote down vote up
constructor(
    args: any[],
    constructorRef: Type<any> = null,
    handler: Function = null,
  ) {
    super(args, constructorRef, handler);
    // All graphql resolvers have 4 args: Root, Args, Context, Info
    // Only Mercurius Loaders have only 2 args: Queries and Context
    this.isLoaderContext = isLoaderContext(args);
  }
Example #18
Source File: api-pagination.response.ts    From nest-js-quiz-manager with MIT License 6 votes vote down vote up
ApiPaginatedResponse = <TModel extends Type<any>>(
  options: IPaginatedDecoratorApiResponse,
) => {
  return applyDecorators(
    ApiExtraModels(PaginatedDto),
    ApiOkResponse({
      description: options.description || 'Successfully received model list',
      schema: {
        allOf: [
          { $ref: getSchemaPath(PaginatedDto) },
          {
            properties: {
              items: {
                type: 'array',
                items: { $ref: getSchemaPath(options.model) },
              },
              meta: {
                type: 'any',
                default: {
                  totalItems: 2,
                  itemCount: 2,
                  itemsPerPage: 2,
                  totalPages: 1,
                  currentPage: 1,
                },
              },
            },
          },
        ],
      },
    }),
  );
}
Example #19
Source File: reflector.service.d.ts    From nest-jaeger with MIT License 6 votes vote down vote up
/**
     * Retrieve metadata for a specified key for a specified target.
     *
     * @example
     * `const roles = this.reflector.get<string[]>('roles', context.getHandler());`
     *
     * @param metadataKey lookup key for metadata to retrieve
     * @param target context (decorated object) to retrieve metadata from
     *
     */
    get<TResult = any, TKey = any>(metadataKey: TKey, target: Type<any> | Function): TResult;
Example #20
Source File: base.command.ts    From relate with GNU General Public License v3.0 5 votes vote down vote up
// Any nestjs module should be a valid command module.
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    protected abstract commandModule: Type<any>;
Example #21
Source File: module-ref.d.ts    From nest-jaeger with MIT License 5 votes vote down vote up
introspect<T = any>(token: Type<T> | string | symbol): IntrospectionResult;
Example #22
Source File: pact-consumer-core.module.ts    From nestjs-pact with MIT License 5 votes vote down vote up
private static createAsyncOptionsProviders(options: PactConsumerModuleAsyncOptions): Provider[] {
    if (options.useFactory) {
      return [
        {
          provide: PactModuleProviders.ConsumerOptions,
          useFactory: async () => {
            const { consumer } = await options.useFactory();
            return consumer;
          },
          inject: options.inject || [],
        },
        {
          provide: PactModuleProviders.PublicationOptions,
          useFactory: async () => {
            const { publication } = await options.useFactory();
            return publication;
          },
          inject: options.inject || [],
        },
      ];
    }

    const inject = [(options.useClass || options.useExisting) as Type<PactConsumerOverallOptions>];

    return [
      {
        provide: PactModuleProviders.ConsumerOptions,
        useFactory: async (optionsFactory: PactConsumerOptionsFactory) => {
          const { consumer } = await optionsFactory.createPactConsumerOptions();

          return consumer;
        },
        inject,
      },
      {
        provide: PactModuleProviders.PublicationOptions,
        useFactory: async (optionsFactory: PactConsumerOptionsFactory) => {
          const { publication } = await optionsFactory.createPactConsumerOptions();

          return publication;
        },
        inject,
      },
    ];
  }
Example #23
Source File: module-ref.d.ts    From nest-jaeger with MIT License 5 votes vote down vote up
abstract resolve<TInput = any, TResult = TInput>(typeOrToken: Type<TInput> | string | symbol, contextId?: ContextId, options?: {
        strict: boolean;
    }): Promise<TResult>;
Example #24
Source File: pact.provider.ts    From nestjs-pact with MIT License 5 votes vote down vote up
PactProvider = ProviderFactory.create<Type<Pact>>(PactModuleProviders.Pact, Pact)
Example #25
Source File: types.ts    From radiopanel with GNU General Public License v3.0 5 votes vote down vote up
export function Paginate<T>(classRef: Type<T>): Type<Paginated<T>> {
	return classRef as any;
}
Example #26
Source File: global-id-field.resolver.ts    From nestjs-relay with MIT License 5 votes vote down vote up
export function GlobalIdFieldResolver<T>(
  classRef: Type<T>,
  idFieldOptions?: GlobalIdFieldOptions,
): Type<GlobalIdFieldResolver> {
  const globalIdFieldOptions = idFieldOptions || {};

  @Resolver(classRef, { isAbstract: true })
  abstract class GlobalIdFieldResolverHost {
    @GlobalIdField(globalIdFieldOptions)
    id(@Parent() parent: ResolverParent, @Info() info: ResolverInfo): ResolvedGlobalId {
      if (!parent || !parent.id) {
        throw new Error(`Cannot resolve id when 'parent' or 'parent.id' is null`);
      }
      switch (typeof parent.id) {
        case 'object':
          return parent.id;
        case 'string':
          return new ResolvedGlobalId({
            type: info.parentType.name,
            id: parent.id,
          });
        case 'number':
          return new ResolvedGlobalId({
            type: info.parentType.name,
            id: parent.id.toString(),
          });
      }
    }
  }
  return GlobalIdFieldResolverHost as Type<GlobalIdFieldResolver>;
}
Example #27
Source File: testUtils.ts    From office-hours with GNU General Public License v3.0 5 votes vote down vote up
export function setupIntegrationTest(
  module: Type<any>,
  modifyModule?: ModuleModifier,
): (u?: SupertestOptions) => supertest.SuperTest<supertest.Test> {
  let app: INestApplication;
  let jwtService: JwtService;
  let conn: Connection;

  beforeAll(async () => {
    let testModuleBuilder = Test.createTestingModule({
      imports: [
        module,
        LoginModule,
        TestTypeOrmModule,
        TestConfigModule,
        RedisModule.register([
          { name: 'pub' },
          { name: 'sub' },
          { name: 'db' },
        ]),
      ],
    })
      .overrideProvider(TwilioService)
      .useValue(mockTwilio);

    if (modifyModule) {
      testModuleBuilder = modifyModule(testModuleBuilder);
    }
    const testModule = await testModuleBuilder.compile();

    app = testModule.createNestApplication();
    addGlobalsToApp(app);
    jwtService = testModule.get<JwtService>(JwtService);
    conn = testModule.get<Connection>(Connection);
    await app.init();
  });

  afterAll(async () => {
    await app.close();
    await conn.close();
  });

  beforeEach(async () => {
    await conn.synchronize(true);
  });

  return (options?: SupertestOptions): supertest.SuperTest<supertest.Test> => {
    const agent = supertest.agent(app.getHttpServer());
    if (options?.userId) {
      const token = jwtService.sign({ userId: options.userId });
      agent.set('Cookie', [`auth_token=${token}`]);
    }
    return agent;
  };
}
Example #28
Source File: module-ref.d.ts    From nest-jaeger with MIT License 5 votes vote down vote up
abstract get<TInput = any, TResult = TInput>(typeOrToken: Type<TInput> | string | symbol, options?: {
        strict: boolean;
    }): TResult;
Example #29
Source File: strategy.explorer.ts    From nestjs-oauth2-server-module with MIT License 5 votes vote down vote up
extractMetadata(instance: Object, metadataKey: string): Type<any> {
        if (!instance.constructor) {
            return;
        }
        const metadata = Reflect.getMetadata(metadataKey, instance.constructor);
        return metadata ? (instance.constructor as Type<any>) : undefined;
    }