tsyringe#injectable TypeScript Examples

The following examples show how to use tsyringe#injectable. 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: ListProviderAppointmentsService.ts    From gobarber-api with MIT License 6 votes vote down vote up
@injectable()
class ListProviderAppointmentsService {
  constructor(
    @inject('AppointmentsRepository')
    private appointmentsRepository: IAppointmentRepository,

    @inject('CacheProvider')
    private cacheProvider: ICacheProvider,
  ) {}

  public async execute({
    provider_id,
    day,
    month,
    year,
  }: IRequest): Promise<Appointment[]> {
    const cacheKey = `provider-appointments:${provider_id}:${year}-${month}-${day}`;

    let appointments = await this.cacheProvider.recover<Appointment[]>(
      cacheKey,
    );

    if (!appointments) {
      appointments = await this.appointmentsRepository.findAllInDayFromProvider(
        {
          provider_id,
          day,
          month,
          year,
        },
      );

      await this.cacheProvider.save(cacheKey, classToClass(appointments));
    }

    return appointments;
  }
}
Example #2
Source File: CreateCustomerService.ts    From rocketseat-gostack-11-desafios with MIT License 6 votes vote down vote up
@injectable()
class CreateCustomerService {
  constructor(
    @inject('CustomersRepository')
    private customersRepository: ICustomersRepository,
  ) {}

  public async execute({ name, email }: IRequest): Promise<Customer> {
    const checkCustomerExists = await this.customersRepository.findByEmail(
      email,
    );

    if (checkCustomerExists) {
      throw new AppError('Email address already used.');
    }

    const customer = await this.customersRepository.create({ name, email });

    return customer;
  }
}
Example #3
Source File: ListProvidersService.ts    From hotseat-api with MIT License 6 votes vote down vote up
@injectable()
class ListProvidersService {
  constructor(
    @inject('UsersRepository')
    private usersRepository: IUsersRepository,

    @inject('CacheProvider')
    private cacheProvider: ICacheProvider,
  ) {}

  public async execute({ exceptUserId }: IRequest): Promise<User[]> {
    const providersListCacheKey = getProvidersListCacheKey(exceptUserId);

    let providers = await this.cacheProvider.get<User[]>(providersListCacheKey);

    if (!providers) {
      providers = await this.usersRepository.findProviders({
        exceptUserId,
      });

      await this.cacheProvider.save<User[]>(
        providersListCacheKey,
        classToClass(providers),
      );
    }

    return providers;
  }
}
Example #4
Source File: ConsentDetails.ts    From ADR-Gateway with MIT License 6 votes vote down vote up
@injectable()
export class ConsentDetailsMiddleware {

    constructor(
        @inject("Logger") private logger: winston.Logger,
        @inject("DataHolderMetadataProvider") private dataHolderMetadataProvider: DataHolderMetadataProvider<DataholderMetadata>,
        @inject("AdrGatewayConfig") private config:(() => Promise<AdrGatewayConfig>),
        // private tokenRequestor: TokenRequestor,
        private consentManager:ConsentRequestLogManager
    ) { }

    handler = () => {
    
        let Responder = async (req:express.Request,res:express.Response) => {
    
            let m:any = <any>matchedData(req);

            let consent = await this.consentManager.GetConsentOrUndefined(m.consentId);
    
            // TODO do redirect instead of merely describing one

            if (consent) {
                return res.json(await SerializeConsentDetails(consent,this.dataHolderMetadataProvider))          
            } else {
                return res.status(404).json([])
            }
        };
    
        // decide whether to validate based on body or query parameters
        // TODO add client authorization
        return _.concat(
            [
                param('consentId').exists().toInt(),
                Responder
            ])
    }

}
Example #5
Source File: CreateItemService.ts    From ecoleta with MIT License 6 votes vote down vote up
@injectable()
class CreateItemService {
  constructor(
    @inject('ItemsRepository')
    private itemsRepository: IItemsRepository,
  ) {}

  public async execute({ title, image }: IRequest): Promise<Item> {
    const checkItemExists = await this.itemsRepository.findByTitle(title);

    if (checkItemExists) throw new AppError('Product already exists');

    const product = await this.itemsRepository.create({
      title,
      image,
    });

    return product;
  }
}
Example #6
Source File: block-service.ts    From hexon with GNU General Public License v3.0 6 votes vote down vote up
@injectable()
@singleton()
export class BlockService {
  public static KEY = "blocklist"
  constructor(
    @inject(StorageService) private _storage: StorageService,
    @inject(LogService) private _logService: LogService
  ) {
    this._logService.setScope("block-service")
  }

  private _toStorage(info: BlockInfo) {
    this._storage.set(BlockService.KEY, info)
  }
  private _fromStorage(): BlockInfo {
    return this._storage.get(BlockService.KEY) || []
  }

  isBlocked(token: string) {
    this._logService.log("query token")
    return this._fromStorage().includes(token)
  }

  block(tokens: string[]) {
    const blocked = this._fromStorage()
    blocked.push(...tokens)
    this._toStorage(blocked)
    this._logService.log("block tokens", tokens.length)
  }

  clear() {
    this._toStorage([])
    // FIXME 按照过期时间清理
    this._logService.log("clear block")
  }
}
Example #7
Source File: AuthenticationDataSource.ts    From rn-clean-architecture-template with MIT License 6 votes vote down vote up
@injectable()
export class ApiAuthenticationDataSource
  implements RemoteAuthenticationDataSource {
  constructor(
    @inject('ApiProvider')
    private readonly provider: RxRemoteProvider,
  ) {}
  signIn(body: SignInRequestData): Observable<ApiResult<SignInResponseData>> {
    return this.provider
      .post<ApiResult<SignInResponseData>>('login_url', body)
      .pipe(map((response) => response.data));
  }
}
Example #8
Source File: ListProviderAppointmentsService.ts    From gobarber-project with MIT License 6 votes vote down vote up
@injectable()
class ListProvidersAppointmentsService {
  constructor(
    @inject('AppointmentsRepository')
    private appointmentsRepository: IAppointmentsRepository,

    @inject('CacheProvider')
    private cacheProvider: ICacheProvider,
  ) {}

  public async execute({
    provider_id,
    day,
    month,
    year,
  }: IRequest): Promise<Appointment[]> {
    const cacheKey = `provider-appointments:${provider_id}:${year}-${month}-${day}`;

    let appointments = await this.cacheProvider.recover<Appointment[]>(
      cacheKey,
    );

    if (!appointments) {
      appointments = await this.appointmentsRepository.findAllInDayFromProvider(
        {
          provider_id,
          day,
          month,
          year,
        },
      );

      await this.cacheProvider.save(cacheKey, classToClass(appointments));
    }
    return appointments;
  }
}
Example #9
Source File: ListProvidersService.ts    From GoBarber with MIT License 6 votes vote down vote up
@injectable()
class ListProvidersService {
  private usersRepository: IUsersRepository;

  private cacheProvider: ICacheProvider;

  constructor(
    @inject('UsersRepository')
    usersRepository: IUsersRepository,

    @inject('CacheProvider')
    cacheProvider: ICacheProvider,
  ) {
    this.usersRepository = usersRepository;
    this.cacheProvider = cacheProvider;
  }

  public async execute({ user_id }: IRequest): Promise<User[]> {
    let users = await this.cacheProvider.recover<User[]>(
      `providers-list:${user_id}`,
    );

    if (!users) {
      users = await this.usersRepository.findAllProviders({
        except_user_id: user_id,
      });

      await this.cacheProvider.save({
        key: `providers-list:${user_id}`,
        value: users,
      });
    }

    return users;
  }
}
Example #10
Source File: CreateAppointmentService.ts    From gobarber-api with MIT License 5 votes vote down vote up
@injectable()
class CreateAppointmentService {
  constructor(
    @inject('AppointmentsRepository')
    private appointmentsRepository: IAppoitmentsRepository,

    @inject('NotificationsRepository')
    private notificationsRepository: INotificationsRepository,

    @inject('CacheProvider')
    private cacheProvider: ICacheProvider,
  ) {}

  public async execute({
    date,
    provider_id,
    user_id,
  }: IRequest): Promise<Appointment> {
    const appointmentDate = startOfHour(date);

    if (isBefore(appointmentDate, Date.now())) {
      throw new AppError("You cant't create an appointment on past date");
    }

    if (user_id === provider_id) {
      throw new AppError("You can't create an appointment with yourself");
    }

    if (getHours(appointmentDate) < 8 || getHours(appointmentDate) > 17) {
      throw new AppError(
        'You can only create appointments between 8am and 5pm',
      );
    }

    const findAppointmentInSameDate = await this.appointmentsRepository.findByDate(
      {
        date: appointmentDate,
        provider_id,
      },
    );

    if (findAppointmentInSameDate) {
      throw new AppError('This appointment is already booked');
    }

    const appointment = await this.appointmentsRepository.create({
      user_id,
      provider_id,
      date: appointmentDate,
    });

    const dateFormated = format(appointmentDate, "dd/MM/yyyy 'às' HH:mm'h'");

    await this.notificationsRepository.create({
      recipient_id: provider_id,
      content: `Novo agendamento para dia ${dateFormated}.`,
    });

    await this.cacheProvider.invalidate(
      `provider-appointments:${provider_id}:${format(
        appointmentDate,
        'yyyy-M-d',
      )}`,
    );

    return appointment;
  }
}
Example #11
Source File: CreateOrderService.ts    From rocketseat-gostack-11-desafios with MIT License 5 votes vote down vote up
@injectable()
class CreateProductService {
  constructor(
    @inject('OrdersRepository')
    private ordersRepository: IOrdersRepository,

    @inject('ProductsRepository')
    private productsRepository: IProductsRepository,

    @inject('CustomersRepository')
    private customersRepository: ICustomersRepository,
  ) {}

  public async execute({ customer_id, products }: IRequest): Promise<Order> {
    const customer = await this.customersRepository.findById(customer_id);

    if (!customer) {
      throw new AppError('Customer not found');
    }

    const productsWithPrice = await this.productsRepository.findAllById(
      products.map(product => ({ id: product.id })),
    );

    if (products.length !== productsWithPrice.length) {
      throw new AppError('Product not found');
    }

    products.forEach(product => {
      const databaseQuantity = productsWithPrice.find(
        ({ id }) => id === product.id,
      )?.quantity;

      if ((databaseQuantity || 0) < product.quantity) {
        throw new AppError('Quantity invalid');
      }
    });

    const order = await this.ordersRepository.create({
      customer,
      products: products.map(product => ({
        product_id: product.id,
        price:
          productsWithPrice.find(({ id }) => id === product.id)?.price || 0,
        quantity: product.quantity,
      })),
    });

    await this.productsRepository.updateQuantity(products);

    return order;
  }
}
Example #12
Source File: CreateAppointmentService.ts    From hotseat-api with MIT License 5 votes vote down vote up
@injectable()
class CreateAppointmentService {
  constructor(
    @inject('AppointmentsRepository')
    private appointmentsRepository: IAppointmentsRepository,

    @inject('NotificationsRepository')
    private notificationsRepository: INotificationsRepository,

    @inject('CacheProvider')
    private cacheProvider: ICacheProvider,
  ) {}

  public async execute({
    provider_id,
    customer_id,
    date,
    type,
  }: IRequest): Promise<Appointment> {
    const appointmentDate = startOfHour(date);

    const appointmentInTheSameDate = await this.appointmentsRepository.findByDate(
      appointmentDate,
    );

    if (
      appointmentInTheSameDate &&
      appointmentInTheSameDate.provider_id === provider_id
    ) {
      throw new AppError("There's already a appointment booked in that date");
    }

    const customerIsTheProvider = provider_id === customer_id;

    if (customerIsTheProvider) {
      throw new AppError("You can't book an appointment with yourself");
    }

    const hasValidDate = isAfter(appointmentDate, new Date(Date.now()));

    if (!hasValidDate) {
      throw new AppError("You can't book an appointment in a past date");
    }

    const appointmentHours = getHours(appointmentDate);
    const isInBusinessHoursRange =
      appointmentHours >= BUSINESS_START_HOUR &&
      appointmentHours <= BUSINESS_LIMIT_HOUR;

    if (!isInBusinessHoursRange) {
      throw new AppError(
        "You can't book an appointment in a hour outside the business hours range",
      );
    }

    const appointment = this.appointmentsRepository.create({
      provider_id,
      customer_id,
      date: appointmentDate,
      type,
    });

    const notificationAppointmentDate = format(
      appointmentDate,
      'dd-MM-yyyy HH:mm',
    );

    await this.notificationsRepository.create({
      content: `You have an appointment schedule to ${notificationAppointmentDate}`,
      recipient_id: provider_id,
    });

    this.cacheProvider.invalidate(
      getProviderAppointmentsListCacheKey(provider_id, appointmentDate),
    );

    return appointment;
  }
}
Example #13
Source File: ConsentDeletion.ts    From ADR-Gateway with MIT License 5 votes vote down vote up
@injectable()
class ConsentDeletionMiddleware {

    constructor(
        @inject("Logger") private logger: winston.Logger,
        private connector: DefaultConnector,
        @inject("AdrGatewayConfig") private config:(() => Promise<AdrGatewayConfig>),
        private consentManager:ConsentRequestLogManager
    ) { }

    DeleteConsent = async (consentId:number) => {
        let consent:ConsentRequestLog;
        try {
            consent = await this.consentManager.GetConsent(consentId);   // TODO consider returning undefined from GetConsent??
        } catch {
            return {
                found: false,
                deleted: false
            }
        }

        if (!consent.IsCurrent()) return {
            found: true,
            deleted: false
        };

        await this.consentManager.RevokeConsent(consent,"DataRecipient");

        return {found: true, deleted: true, consent}
    }

    handler = () => {
        let validationErrorMiddleware = (req:express.Request,res:express.Response,next: NextFunction) => {
            const errors = validationResult(req);
            if (!errors.isEmpty()) {
              return res.status(400).json({ errors: errors.array() });
            }
            next();
        }
    
        let Responder = async (req:express.Request,res:express.Response) => {
    
            let m:{consentId:number} = <any>matchedData(req);

            this.logger.info(`Requested revocation of consent: ${m.consentId}`);

            let status:{found:boolean,deleted:boolean,consent?:ConsentRequestLog} = await this.DeleteConsent(m.consentId);
    
            if (!status.found) return res.status(404).send();
            if (!status.deleted) return res.status(409).send();

            try {
                // this is purposely not awaited. It should not block the sending of a 200 response.
                this.connector.PropagateRevokeConsent(status.consent).GetWithHealing().catch(err => {
                    this.connector.logger.error(err,{message:"Could not propagate consent revocation", meta: status.consent})
                })
            } finally {
                return res.status(200).send();
            }

        };
    
        // decide whether to validate based on body or query parameters
        return _.concat(
            [
                param('consentId').isInt({min:0}),
                validationErrorMiddleware,
                Responder
            ])
    }

}
Example #14
Source File: CreatePointService.ts    From ecoleta with MIT License 5 votes vote down vote up
@injectable()
class CreatePointService {
  constructor(
    @inject('PointsRepository')
    private pointsRepository: IPointsRepository,

    @inject('ItemsRepository')
    private itemsRepository: IItemsRepository,
  ) {}

  public async execute({
    name,
    image,
    email,
    whatsapp,
    latitude,
    longitude,
    uf,
    city,
    items,
  }: IRequest): Promise<Point> {
    const checkItemsExists = await this.itemsRepository.findAllById(items);

    if (items.length !== checkItemsExists.length)
      throw new AppError('Item not found');

    const point = await this.pointsRepository.create({
      city,
      image,
      email,
      latitude,
      longitude,
      name,
      uf,
      whatsapp,
      itemsId: items,
    });

    await fs.promises.rename(
      path.resolve(uploadConfig.uploadsFolder, image),
      path.resolve(uploadConfig.photosFolder, image),
    );

    return point;
  }
}
Example #15
Source File: auth-storage-service.ts    From hexon with GNU General Public License v3.0 5 votes vote down vote up
@injectable()
@singleton()
export class AuthStorageService {
  public static KEY = "authinfo"
  constructor(
    @inject(StorageService) private _storage: StorageService,
    @inject(LogService) private _logService: LogService
  ) {
    this._logService.setScope("auth-storage-service")
  }

  private _toStorage(info: IAuthInfo) {
    this._storage.set(AuthStorageService.KEY, info)
  }

  private _fromStorage(): IAuthInfo {
    const {
      secret = "secret",
      expiresIn = "1h",
      refreshableIn = "7d",
    } = this._storage.get(AuthStorageService.KEY) || {}
    return { secret, expiresIn, refreshableIn }
  }

  public setAuthInfo(info: IAuthInfo) {
    this._toStorage(info)
    this._logService.log(`set auth info`)
  }

  public getSecret() {
    const s = this._fromStorage().secret
    this._logService.log(`get secret`)
    return s
  }

  public getAuthInfo(): IAuthInfo {
    const s = this._fromStorage()
    this._logService.log(`get auth info`)
    return s
  }
}
Example #16
Source File: CreateAppointmentService.ts    From gobarber-project with MIT License 5 votes vote down vote up
@injectable()
class CreateAppointmentService {
  constructor(
    @inject('AppointmentsRepository')
    private appointmentsRepository: IAppointmentsRepository,

    @inject('NotificationsRepository')
    private notificationsRepository: INotificationsRepository,

    @inject('CacheProvider')
    private cacheProvider: ICacheProvider,
  ) {}

  public async execute({
    provider_id,
    user_id,
    date,
  }: IRequest): Promise<Appointment> {
    const appointmentDate = startOfHour(date);

    if (isBefore(appointmentDate, Date.now())) {
      throw new AppError("You can't create an appointment on a past date");
    }

    if (user_id === provider_id) {
      throw new AppError("You can't create an appointment with yourself");
    }

    if (getHours(appointmentDate) < 8 || getHours(appointmentDate) > 17) {
      throw new AppError(
        'You can only create appointments between 8am and 5pm',
      );
    }

    const findAppoitmentInSameDate = await this.appointmentsRepository.findByDate(
      appointmentDate,
      provider_id,
    );

    if (findAppoitmentInSameDate) {
      throw new AppError('This appointment is already booked');
    }

    const appointment = await this.appointmentsRepository.create({
      provider_id,
      user_id,
      date: appointmentDate,
    });

    const dateFormatted = format(appointmentDate, "dd/MM/yyyy 'às' HH:mm'h'");

    await this.notificationsRepository.create({
      recipient_id: provider_id,
      content: `Novo agendamento para dia ${dateFormatted}`,
    });

    await this.cacheProvider.invalidate(
      `provider-appointments:${provider_id}:${format(
        appointmentDate,
        'yyyy-M-d',
      )}`,
    );

    return appointment;
  }
}
Example #17
Source File: CreateAppointmentService.ts    From GoBarber with MIT License 5 votes vote down vote up
@injectable()
class CreateAppointmentService {
  private appointmentsRepository: IAppointmentsRepository;

  private notificationsRepository: INotificationsRepository;

  private cacheProvider: ICacheProvider;

  constructor(
    @inject('AppointmentsRepository')
    appointmentsRepository: IAppointmentsRepository,

    @inject('NotificationsRepository')
    notificationsRepository: INotificationsRepository,

    @inject('CacheProvider')
    cacheProvider: ICacheProvider,
  ) {
    this.appointmentsRepository = appointmentsRepository;
    this.notificationsRepository = notificationsRepository;
    this.cacheProvider = cacheProvider;
  }

  public async execute({
    provider_id,
    user_id,
    date,
  }: IRequest): Promise<Appointment> {
    const appointmentDate = startOfHour(date);

    if (isBefore(appointmentDate, Date.now())) {
      throw new AppError("You can't book appointments in past dates");
    }

    if (provider_id === user_id) {
      throw new AppError("You can't book appointments with yourself");
    }

    if (getHours(appointmentDate) < 8 || getHours(appointmentDate) > 17) {
      throw new AppError("You can't book appointments outside commercial time");
    }

    const findAppointmentInSameDate = await this.appointmentsRepository.findByDate(
      appointmentDate,
      provider_id,
    );

    if (findAppointmentInSameDate) {
      throw new AppError('This appointment is already booked');
    }

    const appointment = await this.appointmentsRepository.create({
      provider_id,
      user_id,
      date: appointmentDate,
    });

    const dateFormatted = format(appointmentDate, "dd/MM/yyyy 'às' HH:mm'h'");

    await this.notificationsRepository.create({
      recipient_id: provider_id,
      content: `Novo agendamento para ${dateFormatted}`,
    });

    await this.cacheProvider.invalidate(
      `provider-appointments:${provider_id}:${format(
        appointmentDate,
        'd-M-yyyy',
      )}`,
    );

    return appointment;
  }
}