How to use the typedi.Service function in typedi

To help you get started, we’ve selected a few typedi 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 youzan / zan-proxy / src / core / App / services / profile.ts View on Github external
}

const defaultProfile: Profile = {
  // 是否启用host解析
  enableHost: true,
  // 是否启用转发规则
  enableRule: true,
  // 工程路径配置
  projectPath: {},
};
/**
 * 代理运转需要的规则数据
 * 代理端口、超时时间、gitlab token、工程路径、是否启用转发规则
 * Created by tsxuehu on 8/3/17.
 */
@Service()
export class ProfileService extends EventEmitter {
  private userProfileMap: object;
  private clientIpUserMap: object;
  private profileSaveDir: string;
  private clientIpUserMapSaveFile: string;
  constructor(appInfoService: AppInfoService) {
    super();
    // userId -> profile
    this.userProfileMap = {};
    // clientIp -> userId
    this.clientIpUserMap = {};

    const proxyDataDir = appInfoService.getProxyDataDir();
    this.profileSaveDir = path.join(proxyDataDir, 'profile');
    this.clientIpUserMapSaveFile = path.join(proxyDataDir, 'clientIpUserMap.json');
github NoQuarterTeam / split / packages / api / src / seed.ts View on Github external
import "reflect-metadata"
import { createDbConnection } from "./db"
import { User } from "./modules/user/user.entity"
import { Group } from "./modules/group/group.entity"

import Container, { Service } from "typedi"
import { CostService } from "./modules/cost/cost.service"
import { CostInput } from "./modules/cost/inputs/cost.input"

@Service()
class Seeds {
  constructor(private readonly costService: CostService) {}
  async create() {
    console.log("Creating seeds 🌱")
    await createDbConnection()
    const group = await Group.create({
      name: "Marco Polostraat",
      currency: "Euro",
    }).save()
    const user1 = await User.create({
      firstName: "Jack",
      lastName: "Clackett",
      email: "jack@noquarter.co",
      password: "password",
      groupId: group.id,
    }).save()
github NoQuarterTeam / split / packages / api / src / modules / user / user.repository.ts View on Github external
import { Service } from "typedi"

import { User } from "./user.entity"
import { Group } from "../group/group.entity"

@Service()
export class UserRepository {
  findAll(group: Group): Promise {
    return User.find({
      where: { group },
      order: { firstName: "DESC" },
    })
  }

  async findById(userId: string): Promise {
    const user = await User.findOne(userId)
    if (!user) throw new Error("User not found")
    return user
  }

  async findByEmail(email: string): Promise {
    return User.findOne({ where: { email } })
github mgm-interns / team-radio / server / src / subscription / SubscriptionManager.ts View on Github external
import { Context, IAnonymousContext, IAuthenticatedContext } from 'config';
import { PubSub } from 'graphql-yoga';
import { UserRepository } from 'repositories';
import { Logger } from 'services';
import { RealTimeStationsManager, StationTopic } from 'subscription';
import { Inject, Service, Container } from 'typedi';
import { InjectRepository } from 'typeorm-typedi-extensions';

@Service()
export class SubscriptionManager {
  @Inject()
  private logger: Logger;

  @InjectRepository()
  private userRepository: UserRepository;

  private _pubSub = new PubSub();

  public get pubSub() {
    return this._pubSub;
  }

  getOnConnectingHandler() {
    return (headers: SubscriptionHeader): SubscriptionHeader => {
      this.logger.info(`Socket client connecting with headers`, headers);
github chanlito / untitled / server / api / auth / auth.service.ts View on Github external
import moment from 'moment';
import { AuthChecker, ResolverData } from 'type-graphql';
import { Service } from 'typedi';

import {
  Prisma,
  SecurityTokenType,
  SecurityTokenWhereInput,
} from '../../generated/prisma-client';
import { Context } from '../../lib/context';
import { Mailer } from '../../lib/mailer';
import { uid } from '../../lib/uid';
import { User } from '../user';
import { SignUpInput } from './auth.args';

@Service()
export class AuthService implements AuthCheckerService {
  constructor(private readonly db: Prisma, private readonly mailer: Mailer) {}

  async authChecker(
    { context: { currentUser } }: ResolverData,
    roles: string[],
  ) {
    if (roles.length === 0) return !!currentUser;
    if (!currentUser) return false;
    if (roles.includes(currentUser.role)) return true;
    return false;
  }

  async comparePasswords(password: string, passwordHash: string) {
    return compare(password, passwordHash);
  }
github swimlane / node-microservice-demo / petstore / src / services / MongoService.ts View on Github external
import { Service, Inject } from 'typedi';
import { Mongo } from '../config/Mongo';

@Service()
export abstract class MongoService {

  @Inject()
  mongodb: Mongo;

  abstract collectionName: string;

  async collection(name?: string) {
    let db = await this.mongodb.db();
    return db.collection(name || this.collectionName);
  }

  async insertOne(document: any) {
    let col = await this.collection();
    return col.insertOne(document);
  }
github goldcaddy77 / warthog-starter / src / project / project.service.ts View on Github external
import { Service } from 'typedi';
import { Repository } from 'typeorm';
import { InjectRepository } from 'typeorm-typedi-extensions';

import { BaseService } from 'warthog';

import { Project } from './project.model';

@Service('ProjectService')
export class ProjectService extends BaseService {
  constructor(@InjectRepository(Project) protected readonly repository: Repository) {
    super(Project, repository);
  }
}
github NoQuarterTeam / split / packages / api / src / modules / share / share.service.ts View on Github external
import { Service } from "typedi"
import { Share } from "./share.entity"
import { ShareInput } from "./share.input"
import { Cost } from "../cost/cost.entity"

@Service()
export class ShareService {
  async bulkCreate(cost: Cost, data: ShareInput[]): Promise {
    await Promise.all(
      data.map(
        async s =>
          await Share.create({
            amount: s.amount,
            userId: s.userId,
            costId: cost.id,
          }).save(),
      ),
    )
    return true
  }

  async bulkRemove(cost: Cost): Promise {
github youzan / zan-proxy / src / core / App / plugin-manager / index.ts View on Github external
import koaMount from 'koa-mount';
import Router from 'koa-router';
import { remove, uniqWith } from 'lodash';
import npm from 'npm';
import path from 'path';
import { Service } from 'typedi';
import { AppInfoService } from '../services';
import Storage from './storage';

export interface Plugin {
  name: string;
  manage: () => koa;
  proxy: () => koa;
}

@Service()
export default class PluginManager {
  private storage: Storage;
  private plugins: Plugin[];
  private dir: string;
  constructor(appInfoService: AppInfoService) {
    this.dir = path.join(appInfoService.getProxyDataDir(), 'plugins');
    this.storage = new Storage(this.getDir());
    this.plugins = this.storage
      .get()
      .filter(p => !p.disabled)
      .reduce((prev, curr) => {
        try {
          const pluginPath = this.getPluginDir(curr.name);
          if (!fs.existsSync(pluginPath)) {
            throw Error(`plugin ${curr.name} not found`);
          }