1

似乎 babel/plugin-proposal-decorators 没有将 tsyringe inject() 和 injectable() 转换为 javascript。这是我用来将我的打字稿文件转换为 javascript 的脚本:

"build": "babel src --extensions \".js,.ts\" --out-dir dist --copy-files --no-copy-ignored"

这是我的 babel.config.js:

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current',
        },
      },
    ],
    '@babel/preset-typescript',
  ],
  plugins: [
    [
      'module-resolver',
      {
        alias: {
          '@modules': './src/modules',
          '@config': './src/config',
          '@shared': './src/shared',
        },
      },
    ],
    ['@babel/plugin-proposal-decorators', { legacy: true }],
  ],
  ignore: ['**/*.spec.ts'],
};

这是在终端返回给我的错误:

TypeInfo not known for "CreateUserService"

这是我的 CreateUserService.ts 文件。这是我用来在我的应用程序中创建新用户的服务,我使用了两个 tsyringes 容器(usersRepository 和 hashProvider)。我使用TypeORM作为我的 ORM:

import 'reflect-metadata';
import { injectable, inject } from 'tsyringe';

import AppError from '@shared/errors/AppError';
import User from '@modules/users/infra/typeorm/entities/User';

// Interfaces
import IUsersRepository from '@modules/users/repositories/IUsersRepository';
import IHashProvider from '@shared/containers/providers/HashProvider/models/IHashProvider';
import ICreateUserDTO from '../dtos/ICreateUserDTO';

@injectable()
export default class CreateUserService {
  constructor(
    @inject('UsersRepository')
    private usersRepository: IUsersRepository,

    @inject('HashProvider')
    private hashProvider: IHashProvider,
  ) {}

  public async execute(data: ICreateUserDTO): Promise<User> {
    const { name, email, password, userType } = data;

    // Use findByEmail method to check if the user exists
    const checkIfUserExists = await this.usersRepository.findByEmail(email);

    // If user exists, it'll return a error
    if (checkIfUserExists) {
      throw new AppError('Email address already used.');
    }

    // Hash the password with bcrypt
    const hashedPassword = await this.hashProvider.createHash(password);

    // Create a new User in database
    const user = await this.usersRepository.create({
      name,
      email,
      password: hashedPassword, // Database will have only the hashed password
      userType,
    });

    return user;
  }
}
4

0 回答 0