How to use the @nestjs/common.Injectable function in @nestjs/common

To help you get started, weโ€™ve selected a few @nestjs/common 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 vendure-ecommerce / vendure / packages / core / src / service / helpers / asset-updater / asset-updater.ts View on Github external
import { idsAreEqual } from '../../../common/utils';
import { Asset, VendureEntity } from '../../../entity';
import { AssetService } from '../../services/asset.service';

export interface EntityWithAssets extends VendureEntity {
    featuredAsset: Asset;
    assets: Asset[];
}

export interface AssetInput {
    featuredAssetId?: string | null;
    assetIds?: string[] | null;
}

@Injectable()
export class AssetUpdater {
    constructor(@InjectConnection() private connection: Connection, private assetService: AssetService) {}

    /**
     * Updates the assets / featuredAsset of an entity, ensuring that only valid assetIds are used.
     */
    async updateEntityAssets(entity: T, input: AssetInput) {
        if (input.assetIds || input.featuredAssetId) {
            if (input.assetIds) {
                const assets = await this.assetService.findByIds(input.assetIds);
                entity.assets = assets;
                const featuredAssetId = input.featuredAssetId;
                if (featuredAssetId) {
                    // If the featuredAsset is also being set, we save the additional
                    // DB query since we already have that asset from the findByIds query.
                    const featuredAsset = assets.find(a => idsAreEqual(a.id, featuredAssetId));
github nestjs / nest / sample / 10-fastify / src / common / middlewares / logger.middleware.ts View on Github external
import { Injectable, NestMiddleware, MiddlewareFunction } from '@nestjs/common';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  resolve(context: string): MiddlewareFunction {
    return (req, res, next) => {
      console.log(`[${context}] Request...`);
      next();
    };
  }
}
github feater-dev / feater / server / src / api / pagination-argument / resolver-pagination-arguments-helper.component.ts View on Github external
import { Injectable } from '@nestjs/common';

@Injectable()
export class ResolverPaginationArgumentsHelper {
    protected readonly defaultLimit = 99999;
    protected readonly maximalLimit = 99999;

    getLimit(limit?: number): number {
        return Math.min(limit || this.defaultLimit, this.maximalLimit);
    }

    getOffset(offset?: number): number {
        return offset || 0;
    }

    getSort(defaultSortKey: string, sortMap: object, sortKey?: string): object {
        if (!sortKey) {
            sortKey = defaultSortKey;
        }
github lightness / github-repo-tools / src / modules / npm-dependency-version / yarn.lock.version.service.ts View on Github external
import { Injectable } from '@nestjs/common';
import * as lockfile from '@yarnpkg/lockfile';
import { OctokitService } from '../octokit/octokit.service';

@Injectable()
export class YarnLockVersionService {

  private REGEXP = /^(.+)\@(.+)$/;

  constructor(
    private octokitService: OctokitService,
  ) {
  }

  public async getVersion(owner, repo, packageName, token?: string): Promise {
    const doc = await this.getYarnLock(owner, repo, token);

    if (doc.type !== 'success') {
      return null;
    }
github vendure-ecommerce / vendure / packages / core / src / service / services / customer-group.service.ts View on Github external
CreateCustomerGroupInput,
    MutationAddCustomersToGroupArgs,
    MutationRemoveCustomersFromGroupArgs,
    UpdateCustomerGroupInput,
} from '@vendure/common/lib/generated-types';
import { ID } from '@vendure/common/lib/shared-types';
import { unique } from '@vendure/common/lib/unique';
import { Connection } from 'typeorm';

import { assertFound } from '../../common/utils';
import { CustomerGroup } from '../../entity/customer-group/customer-group.entity';
import { Customer } from '../../entity/customer/customer.entity';
import { getEntityOrThrow } from '../helpers/utils/get-entity-or-throw';
import { patchEntity } from '../helpers/utils/patch-entity';

@Injectable()
export class CustomerGroupService {
    constructor(@InjectConnection() private connection: Connection) {}

    findAll(): Promise {
        return this.connection.getRepository(CustomerGroup).find({});
    }

    findOne(customerGroupId: ID): Promise {
        return this.connection.getRepository(CustomerGroup).findOne(customerGroupId);
    }

    async create(input: CreateCustomerGroupInput): Promise {
        const customerGroup = new CustomerGroup(input);
        if (input.customerIds) {
            customerGroup.customers = await this.getCustomersFromIds(input.customerIds);
        }
github xmlking / ngx-starter-kit / apps / api / src / app / auth / guards / compose.guard.ts View on Github external
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { AllowGuard } from './allow.guard';
import { AuthGuard } from './auth.guard';
import { RoleGuard } from './role.guard';

@Injectable()
export class ComposeGuard implements CanActivate {
  constructor(private allowGuard: AllowGuard, private authGuard: AuthGuard, private roleGuard: RoleGuard) {}

  async canActivate(context: ExecutionContext): Promise {
    return (
      (await this.allowGuard.canActivate(context)) ||
      ((await this.authGuard.canActivate(context)) && (await this.roleGuard.canActivate(context)))
    );
  }
}
github magishift / magishift.core / packages / crud / src / pipes / dtoValidation.pipe.ts View on Github external
import { GetPropertyType } from '@magishift/util';
import { BadRequestException, Injectable, PipeTransform } from '@nestjs/common';
import { plainToClassFromExist } from 'class-transformer';
import { validate, Validator } from 'class-validator';
import { MagiDto } from 'src/magi.dto';
import { MagiEntity } from 'src/magi.entity';
import { getRepository } from 'typeorm';
import { ColumnMetadata } from 'typeorm/metadata/ColumnMetadata';

const validator = new Validator();

@Injectable()
export class DtoTransformerPipe implements PipeTransform {
  constructor(protected entity: new () => MagiEntity, protected dto: new () => MagiDto) {
    if (!entity || !dto) {
      throw new Error(`${this.constructor.name} must have constructor`);
    }
  }

  async transform(value: any): Promise {
    if (Array.isArray(value)) {
      return await Promise.all(
        value.map(async val => {
          return this.plainToClass(new this.dto(), value);
        }),
      );
    } else {
      return this.plainToClass(new this.dto(), value);
github vendure-ecommerce / vendure / packages / core / src / service / services / auth.service.ts View on Github external
import { AnonymousSession } from '../../entity/session/anonymous-session.entity';
import { AuthenticatedSession } from '../../entity/session/authenticated-session.entity';
import { Session } from '../../entity/session/session.entity';
import { User } from '../../entity/user/user.entity';
import { EventBus } from '../../event-bus/event-bus';
import { AttemptedLoginEvent } from '../../event-bus/events/attempted-login-event';
import { LoginEvent } from '../../event-bus/events/login-event';
import { LogoutEvent } from '../../event-bus/events/logout-event';
import { PasswordCiper } from '../helpers/password-cipher/password-ciper';

import { OrderService } from './order.service';

/**
 * The AuthService manages both authenticated and anonymous Sessions.
 */
@Injectable()
export class AuthService {
    private readonly sessionDurationInMs: number;

    constructor(
        @InjectConnection() private connection: Connection,
        private passwordCipher: PasswordCiper,
        private configService: ConfigService,
        private orderService: OrderService,
        private eventBus: EventBus,
    ) {
        this.sessionDurationInMs = ms(this.configService.authOptions.sessionDuration as string);
    }

    /**
     * Authenticates a user's credentials and if okay, creates a new session.
     */
github bojidaryovchev / nest-angular / src / server / modules / graphql / subscriptions / subscriptions.service.ts View on Github external
import { Injectable, Inject, OnModuleDestroy } from '@nestjs/common';
import { ServerOptions, SubscriptionServer } from 'subscriptions-transport-ws';
import { execute, subscribe, GraphQLSchema } from 'graphql';
import { Server } from 'http';
import * as WebSocket from 'ws';
import { SUBSCRIPTION_SERVER } from './subscriptions.constants';

@Injectable()
export class SubscriptionsService implements OnModuleDestroy {
  private subscriptionServer: SubscriptionServer;

  constructor(@Inject(SUBSCRIPTION_SERVER) private readonly ws: Server) {}

  createSubscriptionServer(
    schema: GraphQLSchema,
    options: ServerOptions = {},
    socketOptions: WebSocket.ServerOptions = {},
  ) {
    this.subscriptionServer = new SubscriptionServer(
      {
        execute,
        subscribe,
        schema,
        ...options,
github BMalaichik / nestjs-starter-kit / packages / backend / src / modules / auth / services / current-user.service.ts View on Github external
import { Injectable } from "@nestjs/common";

import { JwtUserData } from "../auth.interfaces";
import { getNamespace } from "../../shared/cls";


const USER_CLS_KEY = "user";

@Injectable()
export class CurrentUserService {

    public get(): JwtUserData | null {
        const appNamespace = getNamespace();

        const user = appNamespace.get(USER_CLS_KEY);

        return user || null;
    }

    public set(user: JwtUserData): JwtUserData {
        const appNamespace = getNamespace();

        return appNamespace.set(USER_CLS_KEY, user);
    }
}