@anyme/anymejs
Version:
91 lines (88 loc) • 3.71 kB
JavaScript
import { Container, inject } from 'inversify';
import { Cache } from './node_modules/.pnpm/@anyme_cache@0.1.3/node_modules/@anyme/cache/lib/index.js';
import { Config } from './config/index.js';
import { SYMBOLS } from './utils/constants.js';
import InversifyAdapter from './utils/inversify-adapter.js';
import { WinstonLogger } from './core/logger.js';
import { Service } from './core/service.js';
import { Anyme } from './core/app.js';
import { DBManager } from './core/db.js';
import { RedisManager } from './core/redis.js';
class DI {
container = new Container({
autobind: true,
defaultScope: "Singleton",
});
registered = false;
register = (app) => {
if (this.registered)
return this.container.getAsync(SYMBOLS.App);
this.container
.bind(SYMBOLS.IocAdapter)
.toConstantValue(new InversifyAdapter(this.container));
this.container.bind(SYMBOLS.Config).to(Config);
this.container
.bind(SYMBOLS.CoreConfig)
.toResolvedValue(async (config) => await config.loadCore(), [SYMBOLS.Config]);
this.container
.bind(SYMBOLS.Logger)
.toResolvedValue((config) => new WinstonLogger(config.logger).logger, [SYMBOLS.CoreConfig]);
this.container
.bind(SYMBOLS.Cache)
.toResolvedValue((config) => new Cache(config.cache.options), [SYMBOLS.CoreConfig]);
this.container
.bind(SYMBOLS.DB)
.toResolvedValue((logger, config) => new DBManager(logger, config.db), [SYMBOLS.Logger, SYMBOLS.CoreConfig]);
this.container
.bind(SYMBOLS.Redis)
.toResolvedValue((config, logger) => new RedisManager(config.redis, logger), [SYMBOLS.CoreConfig, SYMBOLS.Logger]);
this.container.bind(SYMBOLS.Context).toResolvedValue((config, logger, db, redis, cache) => ({
config,
logger,
db,
redis,
cache,
}), [SYMBOLS.Config, SYMBOLS.Logger, SYMBOLS.DB, SYMBOLS.Redis, SYMBOLS.Cache]);
this.container
.bind(SYMBOLS.Service)
.toResolvedValue((iocAdapter, context) => new Service(app, context, iocAdapter), [SYMBOLS.IocAdapter, SYMBOLS.Context]);
this.container.bind(SYMBOLS.App).to(Anyme);
this.registered = true;
return this.container.getAsync(SYMBOLS.App);
};
inject(identifier, options) {
if (typeof identifier === "string" &&
[
"SSE",
"Logger",
"Redis",
"Cache",
"DB",
"Config",
"Repository",
].includes(identifier)) {
if (identifier === "Repository") {
const entityName = typeof options.entity === "function"
? options.entity.name
: options.entity.name || String(options.entity);
const token = Symbol.for(`Repository_${entityName}`);
if (!this.container.isBound(token))
this.container
.bind(token)
.toResolvedValue((dataSource) => {
return dataSource
.get(options?.dataSource ?? "default")
?.getRepository(options.entity);
}, [SYMBOLS.DB])
.inRequestScope();
return inject(token);
}
return inject(SYMBOLS[identifier]);
}
else
return inject(identifier);
}
}
var di = new DI();
export { di as default };
//# sourceMappingURL=inversify.config.js.map