feat(core): add instance links, introspection and expose request provider

This commit is contained in:
Kamil Myśliwiec
2020-07-01 14:05:32 +02:00
parent 82d0171bcf
commit d59c7b87bd
22 changed files with 286 additions and 252 deletions

View File

@@ -0,0 +1,34 @@
import { Scope } from '@nestjs/common';
import { ModuleRef } from '@nestjs/core';
import { Test, TestingModule } from '@nestjs/testing';
import { expect } from 'chai';
import { ScopedModule, STATIC_FACTORY } from '../src/scoped/scoped.module';
import { ScopedService } from '../src/scoped/scoped.service';
import { TransientService } from '../src/scoped/transient.service';
describe('Providers introspection', () => {
let testingModule: TestingModule;
let moduleRef: ModuleRef;
beforeEach(async () => {
testingModule = await Test.createTestingModule({
imports: [ScopedModule],
}).compile();
moduleRef = testingModule.get(ModuleRef);
});
it('should properly introspect a transient provider', async () => {
const introspectionResult = moduleRef.introspect(TransientService);
expect(introspectionResult.scope).to.be.equal(Scope.TRANSIENT);
});
it('should properly introspect a singleton provider', async () => {
const introspectionResult = moduleRef.introspect(STATIC_FACTORY);
expect(introspectionResult.scope).to.be.equal(Scope.DEFAULT);
});
it('should properly introspect a request-scoped provider', async () => {
const introspectionResult = moduleRef.introspect(ScopedService);
expect(introspectionResult.scope).to.be.equal(Scope.REQUEST);
});
});

View File

@@ -54,13 +54,19 @@ describe('Scoped Instances', () => {
it('should dynamically resolve request-scoped provider', async () => {
const request1 = await testingModule.resolve(ScopedService);
const request2 = await testingModule.resolve(ScopedService);
const request3 = await testingModule.resolve(ScopedService, { id: 1 });
const ctxId = { id: 1 };
const requestProvider = { host: 'localhost' };
testingModule.registerRequestByContextId(requestProvider, ctxId);
const request3 = await testingModule.resolve(ScopedService, ctxId);
const requestFactory = await testingModule.resolve(REQUEST_SCOPED_FACTORY);
expect(request1).to.be.instanceOf(ScopedService);
expect(request2).to.be.instanceOf(ScopedService);
expect(request3).to.not.be.equal(request2);
expect(requestFactory).to.be.true;
expect(request3.request).to.be.equal(requestProvider);
});
it('should dynamically resolve request-scoped controller', async () => {

View File

@@ -1,4 +1,7 @@
import { Injectable, Scope } from '@nestjs/common';
import { Inject, Injectable, Scope } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
@Injectable({ scope: Scope.REQUEST })
export class ScopedService {}
export class ScopedService {
constructor(@Inject(REQUEST) public readonly request) {}
}