Skip to content

Commit

Permalink
chore: Add helper function
Browse files Browse the repository at this point in the history
  • Loading branch information
CGNonofr committed Jul 21, 2022
1 parent a0d6524 commit 76bdfc2
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/tools/injection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { BrandedService, IInstantiationService, _util } from 'vs/platform/instantiation/common/instantiation'

function getInjectedParameters<Ctor extends new (...args: any[]) => InstanceType<Ctor>> (instantiationService: IInstantiationService, ctor: Ctor) {
return instantiationService.invokeFunction((accessor) => {
return _util.getServiceDependencies(ctor).sort((a, b) => a.index - b.index).map(d => accessor.get(d.id))
})
}

declare type GetLeadingNonServiceArgs<Args> = Args extends [...BrandedService[]] ? [] : Args extends [infer A, ...BrandedService[]] ? [A] : Args extends [infer A, ...infer R] ? [A, ...GetLeadingNonServiceArgs<R>] : never

/**
* Takes a class with injected services as parameters and returns a child class that only takes the injector as parameter
* @param ctor The class to inject
* @returns A class that only needs the injector
*/
export function createInjectedClass<Ctor extends new (...args: any[]) => InstanceType<Ctor>>(ctor: Ctor): new (instantiationService: IInstantiationService, ...args: GetLeadingNonServiceArgs<ConstructorParameters<Ctor>>) => InstanceType<Ctor> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _ctor = (ctor as (new (...args: any[]) => any))
return class extends _ctor {
constructor (...args: any[]) {
super(...args.slice(1), ...getInjectedParameters(args[0], ctor))
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any
}

0 comments on commit 76bdfc2

Please sign in to comment.