gpt4 book ai didi

node.js - 我想使用 typedi 在 Service 构造函数中注入(inject) Repositories 容器

转载 作者:行者123 更新时间:2023-12-03 22:30:40 25 4
gpt4 key购买 nike

我想在我的 UserService 中注入(inject)存储库。
但我不知道该怎么做。
我正在使用 typescript、typedi 和 sequelize。
我认为,服务的加载速度比加载器快。
当我尝试注入(inject)我在数据库加载器中设置的存储库时,会发生错误。
像这样的错误: ServiceNotFoundError:在容器中找不到具有“存储库”标识符的服务。在使用前通过显式调用“Container.set”函数或使用“@Service()”装饰器注册它。
所以,我用 console.log 检查了“userRepo”,结果是未定义的。
我还检查了 CreateUser 的 Container.get('repositories'),它是集中加载的。我的意思是,我可以获得我的 Container 实例。
我只是无法在构造函数中加载存储库实例。
我应该怎么做才能在构造函数中加载存储库?
我应该将 sequelize 更改为 typeorm 来加载它吗?

// ** UserService.ts **
import { Inject, Service } from 'typedi';
import { UserRepository } from '../repositories/user.repository';
import { UserCreationAttributes } from '../models/interface/User.interface';
import { User, UserModel, UserStatic } from '../models/User';

@Service()
export default class UserService {
constructor(@Inject('repositories') private userRepo: UserRepository) {}

public async CreateUser(userData: UserCreationAttributes): Promise<boolean> {
try {
await this.userRepo.create(userData);
return true;
} catch (err) {
console.log(err);
return false;
}
}
}
// ** Database Loader **
import { Sequelize } from 'sequelize';
import config from '../config';
import Logger from './logger';
import { UserStatic } from '../models/User';
import { FeedStatic } from '../models/Feed';
import { CommentStatic } from '../models/Comment';
import { VerificationStatic } from '../models/Verification';
import { initializeModels } from '../models';
import { initializeRepositories, Repositories } from '../repositories';
import { Container } from 'typedi';

export interface Models {
User: UserStatic;
Feed: FeedStatic;
Comment: CommentStatic;
Verification: VerificationStatic;
}

export default async function loadSequelize() {
const sequelize = new Sequelize(
config.database,
config.databaseUsername,
config.databasePassword,
{
host: config.databaseHost,
port: config.databasePort,
dialect: 'postgres',
},
);

try {
await sequelize.authenticate();
const models: Models = initializeModels(sequelize);
const repositories: Repositories = initializeRepositories(models);
await sequelize.sync({ force: true });

// This part might be loaded after services were loaded
Container.set('models', models);
Container.set('repositories', repositories);


console.log('load finish');
} catch (err) {
Logger.error(err);
}
}

// ** ./repositories/index.ts **
import { Models } from '../loaders/database';
import { UserRepository } from './user.repository';

export interface Repositories {
UserRepository: UserRepository;
}
export const initializeRepositories = (models: Models): Repositories => {
const usersRepository = new UserRepository(models.User);
const repositories: Repositories = {
UserRepository: usersRepository,
};
return repositories;
};
// ** ./repositories/base.repository.ts **
import { Model, BuildOptions, FindOptions } from 'sequelize/types';
import { IFilter } from './filter/base.filter';

export type RichModel = typeof Model & {
new (values?: Record<string, unknown>, options?: BuildOptions): Model;
};

export interface IMeta {
globalCount: number;
countAfterFiltering: number;
}

export interface IWithMeta<M extends Model> {
meta: IMeta;
data: M[];
}

export abstract class BaseRepository<
M extends Model,
C extends object,
F extends IFilter = IFilter
> {
constructor(public _model: RichModel, private filterFactory: new () => F) {}

private async getCount(where?: Record<string, unknown>): Promise<number> {
const count = await this._model.count({ where });
return count;
}

async getAll(params?: FindOptions, filter?: F): Promise<IWithMeta<M>> {
const { from: offset, count: limit } = filter || {};
const result = await this._model.findAndCountAll({
order: [['id', 'ASC']],
offset: offset,
limit: limit,
...params,
});

const globalCount = await this.getCount();
const countAfterFiltering = ((result.count as unknown) as Record<
string,
unknown
>[]).length;

return {
meta: { globalCount, countAfterFiltering },
data: result.rows as M[],
};
}

async getById(id: string | number): Promise<M> {
const result = await this._model.findByPk(id);
return result as M;
}

async get(where: Record<string, unknown>): Promise<M> {
const result = await this._model.findOne({ where });
return result as M;
}

async updateById(id: string | number, data: C): Promise<M> {
const result = await this._model.update(data, {
where: { id },
returning: true,
});

const [, models] = result;

return models[0] as M;
}

async deleteById(id: string | number): Promise<void> {
await this._model.destroy({
where: { id },
});
}

async create(data: C): Promise<M> {
const model = await this._model.create(data);
return (model as unknown) as M;
}
}
// ** ./repositories/user.repository.ts
import { BaseRepository, IWithMeta, RichModel } from './base.repository';
import { UserModel, UserStatic } from '../models/User';
import { UserCreationAttributes } from '../models/interface/User.interface';
import { IFilter } from './filter/base.filter';
import { UserFilter } from './filter/user.filter';
import { Service } from 'typedi';

@Service()
export class UserRepository extends BaseRepository<
UserModel,
UserCreationAttributes,
IFilter
> {
constructor(private model: UserStatic) {
super(<RichModel>model, IFilter);
}

async getAllUsers(): Promise<IWithMeta<UserModel>> {
const users = await this.getAll();
return users;
}

async getOneByFilter({
email,
password,
}: UserFilter): Promise<UserModel | null> {
const user = await this.model.findOne({
where: {
email,
password,
},
});
return user;
}

async getAdminOneByFilter({
email,
password,
}: UserFilter): Promise<UserModel | null> {
const user = await this.model.findOne({
where: {
email,
password,
isAdmin: true,
},
});
return user;
}
}

最佳答案

首先,试着把你的initializeRepositoriesreflect-metadata 之后立即调用电话调用,以测试执行顺序是否会影响。您不需要在数据库连接文件中调用。
根据我在旧文档中看到的,使用 Container.set要设置所有存储库,您需要提供一个包含对象的数组,其中包含对象的 id。Container.set([{ id: 'userRepository', value: new UserRepository() }])如果您只需要设置一个存储库:Container.set('userRepository', new UserRepository())在上述两种情况下,您都可以使用:Container.get('userRepository') ;
如果您想将引用保留为 repositories您的 initializeRepositories 方法是可以的,但是用法必须是这样的:

@Inject('repositories') repositories: { UserRepository: UserRepository}; 

repositories.UserRepository
如果您不需要通过该方法设置存储库,您可以放置​​一个装饰器 @Service('userRepository')在您的 UserRepository类,它会工作。

关于node.js - 我想使用 typedi 在 Service 构造函数中注入(inject) Repositories 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67309598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com