Skip to content

Commit

Permalink
refactor and generic internal add
Browse files Browse the repository at this point in the history
  • Loading branch information
jacoobes committed Feb 15, 2024
1 parent 07b11b3 commit 4efdbb2
Show file tree
Hide file tree
Showing 7 changed files with 39 additions and 26 deletions.
4 changes: 2 additions & 2 deletions src/core/_internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ export * from './functions';
export type { VoidResult } from '../types/core-plugin';
export { SernError } from './structures/enums';
export { ModuleStore } from './structures/module-store';
export * as DefaultServices from './structures/services';
export { useContainerRaw } from './ioc/base'
export * as __Services from './structures/services';
export { useContainerRaw } from './ioc/base';

6 changes: 3 additions & 3 deletions src/core/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ import type {
UserContextMenuCommandInteraction,
AutocompleteInteraction
} from 'discord.js';
import { ApplicationCommandOptionType, InteractionType } from 'discord.js'
import { ApplicationCommandOptionType, InteractionType } from 'discord.js';
import { PayloadType, PluginType } from './structures';
import assert from 'assert';
import { Payload } from '../types/utility';
import type { Payload } from '../types/utility';

//function wrappers for empty ok / err
export const ok = /* @__PURE__*/ () => Ok.EMPTY;
Expand Down Expand Up @@ -50,7 +50,7 @@ export function treeSearch(
if (options === undefined) return undefined;
//clone to prevent mutation of original command module
const _options = options.map(a => ({ ...a }));
let subcommands = new Set();
const subcommands = new Set();
while (_options.length > 0) {
const cur = _options.pop()!;
switch (cur.type) {
Expand Down
30 changes: 17 additions & 13 deletions src/core/ioc/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,16 @@ export async function __swap_container(c: CoreContainer<Partial<Dependencies>>)
}
containerSubject = c;
}

/**
* @internal
* Don't use this unless you know what you're doing. Destroys old containerSubject if it exists and disposes everything
* then it will swap
*/
export function __add_container(key: string,v : Insertable) {
containerSubject.add({ [key]: v });
}

/**
* Returns the underlying data structure holding all dependencies.
* Exposes methods from iti
Expand All @@ -39,11 +49,10 @@ export function disposeAll(logger: Logging|undefined) {
?.disposeAll()
.then(() => logger?.info({ message: 'Cleaning container and crashing' }));
}

const dependencyBuilder = (container: any, excluded: string[] ) => {
type Insertable =
| ((container: CoreContainer<Dependencies>) => unknown )
type Insertable =
| ((container: CoreContainer<Dependencies>) => unknown)
| object
const dependencyBuilder = (container: any, excluded: string[] ) => {
return {
/**
* Insert a dependency into your container.
Expand Down Expand Up @@ -104,11 +113,6 @@ type ValidDependencyConfig =
| CallbackBuilder
| DependencyConfiguration;

export const insertLogger = (containerSubject: CoreContainer<any>) => {
containerSubject
.upsert({'@sern/logger': () => new DefaultServices.DefaultLogging});
}


/**
* Given the user's conf, check for any excluded/included dependency keys.
Expand All @@ -123,7 +127,7 @@ function composeRoot(
//container should have no client or logger yet.
const hasLogger = conf.exclude?.has('@sern/logger');
if (!hasLogger) {
insertLogger(container);
__add_container('@sern/logger', new DefaultServices.DefaultLogging);
}
//Build the container based on the callback provided by the user
conf.build(container as CoreContainer<Omit<CoreDependencies, '@sern/client'>>);
Expand All @@ -141,13 +145,13 @@ export async function makeDependencies<const T extends Dependencies>
if(typeof conf === 'function') {
const excluded: string[] = [];
conf(dependencyBuilder(containerSubject, excluded));

//We only include logger if it does not exist
const includeLogger =
!excluded.includes('@sern/logger')
&& !containerSubject.getTokens()['@sern/logger'];
&& !containerSubject.hasKey('@sern/logger');

if(includeLogger) {
insertLogger(containerSubject);
__add_container('@sern/logger', new DefaultServices.DefaultLogging);
}

containerSubject.ready();
Expand Down
6 changes: 3 additions & 3 deletions src/core/ioc/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Container } from 'iti';
import { Disposable } from '../';
import * as assert from 'node:assert';
import { Subject } from 'rxjs';
import { DefaultServices, ModuleStore } from '../_internal';
import { __Services, ModuleStore } from '../_internal';
import * as Hooks from './hooks';
import { EventEmitter } from 'node:events';

Expand All @@ -23,11 +23,11 @@ export class CoreContainer<T extends Partial<Dependencies>> extends Container<T,
.subscribe({ complete: unsubscribe });

(this as Container<{}, {}>)
.add({ '@sern/errors': () => new DefaultServices.DefaultErrorHandling,
.add({ '@sern/errors': () => new __Services.DefaultErrorHandling,
'@sern/emitter': () => new EventEmitter({ captureRejections: true }),
'@sern/store': () => new ModuleStore })
.add(ctx => {
return { '@sern/modules': new DefaultServices.DefaultModuleManager(ctx['@sern/store'])};
return { '@sern/modules': new __Services.DefaultModuleManager(ctx['@sern/store'])};
});
}

Expand Down
2 changes: 0 additions & 2 deletions src/handlers/event-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
of,
throwError,
tap,
MonoTypeOperatorFunction,
catchError,
finalize,
map,
Expand All @@ -31,7 +30,6 @@ import { Err, Ok, Result } from 'ts-results-es';
import type { Awaitable } from '../types/utility';
import type { ControlPlugin } from '../types/core-plugin';
import type { AnyModule, CommandMeta, CommandModule, Module, Processed } from '../types/core-modules';
import type { ImportPayload } from '../types/core';
import { disposeAll } from '../core/ioc/base';

function createGenericHandler<Source, Narrowed extends Source, Output>(
Expand Down
5 changes: 2 additions & 3 deletions src/handlers/ready-event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,14 @@ export function readyHandler(
[sEmitter, , log , moduleManager, client]: DependencyList,
allPaths: ObservableInput<string>,
) {
//Todo: add module manager on on ready
const ready$ = fromEvent(client!, 'ready').pipe(once(log));

return concat(ready$, buildModules<AnyModule>(allPaths))
.pipe(callInitPlugins(sEmitter))
.subscribe(({ module, metadata }) => {
register(moduleManager, module, metadata)
.expect(SernError.InvalidModuleType + ' ' + util.inspect(module));
//TODO: TEST ALL MODULES AGAIN
console.log(module)
});
}

Expand Down
12 changes: 12 additions & 0 deletions test/core/ioc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,16 @@ describe('ioc container', () => {
container.ready();
expect(dependency.init).toHaveBeenCalledTimes(1);
})

it('should detect a key already exists', () => {
container.add({ '@sern/client': dependency2 });
expect(container.hasKey('@sern/client')).toBeTruthy()
})


it('should detect a key already exists', () => {
container.add({ '@sern/client': () => dependency2 });
expect(container.hasKey('@sern/client')).toBeTruthy()
})

});

0 comments on commit 4efdbb2

Please sign in to comment.