@nestjs/core#AbstractHttpAdapter TypeScript Examples

The following examples show how to use @nestjs/core#AbstractHttpAdapter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: express-custom.loader.ts    From adminjs-nestjs with MIT License 6 votes vote down vote up
public register(
    admin: AdminJS,
    httpAdapter: AbstractHttpAdapter,
    options: AdminModuleOptions,
  ) {
    // eslint-disable-next-line no-console
    console.log('Custom loader')
    new ExpressLoader().register(admin, httpAdapter, options);
  }
Example #2
Source File: express.loader.ts    From adminjs-nestjs with MIT License 6 votes vote down vote up
public register(
    admin: AdminJS,
    httpAdapter: AbstractHttpAdapter,
    options: AdminModuleOptions,
  ) {
    const app = httpAdapter.getInstance();

    loadPackage('express', '@adminjs/nestjs');
    const adminJsExpressjs = loadPackage('@adminjs/express', '@adminjs/nestjs', () =>
      require('@adminjs/express')
    );
    loadPackage('express-formidable', '@adminjs/nestjs');

    let router;

    if ('auth' in options) {
      loadPackage('express-session', '@adminjs/nestjs');
      router = adminJsExpressjs.buildAuthenticatedRouter(
        admin, options.auth, undefined, options.sessionOptions, options.formidableOptions
      );
    } else {
      router = adminJsExpressjs.buildRouter(admin, undefined, options.formidableOptions);
    }

    // This named function is there on purpose. 
    // It names layer in main router with the name of the function, which helps localize
    // admin layer in reorderRoutes() step.
    // eslint-disable-next-line prefer-arrow/prefer-arrow-functions
    app.use(options.adminJsOptions.rootPath, function admin(req, res, next) {
      return router(req, res, next);
    });
    this.reorderRoutes(app);
  }
Example #3
Source File: auth.service.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
register(httpAdapter: AbstractHttpAdapter): void {
        if (!httpAdapter) {
            return;
        }

        const app: Application = httpAdapter.getInstance();

        this.registerAuthenticationHandlers(app);
    }
Example #4
Source File: apps.service.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
async register(httpAdapter: AbstractHttpAdapter): Promise<void> {
        if (!httpAdapter) {
            return;
        }

        const app = httpAdapter.getInstance();
        const environment = await this.systemProvider.getEnvironment();
        const installedApps = path.join(environment.dataPath, EXTENSION_DIR_NAME, EXTENSION_TYPES.STATIC);

        app.use(STATIC_APP_BASE_ENDPOINT, express.static(installedApps));
    }
Example #5
Source File: files.service.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
register(httpAdapter: AbstractHttpAdapter): void {
        if (!httpAdapter) {
            return;
        }

        const app: Application = httpAdapter.getInstance();

        app.get(`${FILES_BASE_ENDPOINT}/:fileToken/:fileName`, async (req, res): Promise<void> => {
            const {fileToken} = req.params;

            try {
                const {projectName, directory, name} = await TokenService.verify(fileToken);
                const environment = await this.systemProvider.getEnvironment();
                const project = await environment.projects.get(projectName);

                res.sendFile(path.join(project.root, directory, name));
            } catch (e) {
                res.sendStatus(404);
            }
        });
    }
Example #6
Source File: health.service.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
register(httpAdapter: AbstractHttpAdapter): void {
        if (!httpAdapter) {
            return;
        }

        const app = httpAdapter.getInstance();

        app.get(HEALTH_BASE_ENDPOINT, async (_: Request, res: Response) => {
            const environment = await this.systemProvider.getEnvironment();

            res.json({
                relateEnvironmentId: environment.id,
                appRoot: STATIC_APP_BASE_ENDPOINT,
                pid: process.pid,
            });
        });
    }
Example #7
Source File: abstract.loader.ts    From adminjs-nestjs with MIT License 5 votes vote down vote up
public abstract register(
    admin: AdminJS,
    httpAdapter: AbstractHttpAdapter,
    options: AdminModuleOptions,
  );
Example #8
Source File: noop.loader.ts    From adminjs-nestjs with MIT License 5 votes vote down vote up
public register(
    admin: AdminJS,
    httpAdapter: AbstractHttpAdapter,
    options: AdminModuleOptions,
  ) {}
Example #9
Source File: controller.e2e-spec.ts    From nestjs-throttler-storage-redis with MIT License 4 votes vote down vote up
describe.each`
  adapter                 | adapterName
  ${new ExpressAdapter()} | ${'Express'}
  ${new FastifyAdapter()} | ${'Fastify'}
`('$adapterName Throttler', ({ adapter }: { adapter: AbstractHttpAdapter }) => {
  let app: INestApplication;

  beforeAll(async () => {
    await redis.flushall();
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [ControllerModule],
      providers: [
        {
          provide: APP_GUARD,
          useClass: ThrottlerGuard,
        },
      ],
    }).compile();

    app = moduleFixture.createNestApplication(adapter);
    await app.listen(0);
  });

  afterAll(async () => {
    await app.close();
    if (adapter instanceof FastifyAdapter) {
      await redis.quit();
    }
  });

  describe('controllers', () => {
    let appUrl: string;
    beforeAll(async () => {
      appUrl = await app.getUrl();
    });

    /**
     * Tests for setting `@Throttle()` at the method level and for ignore routes
     */
    describe('AppController', () => {
      it('GET /ignored', async () => {
        const response = await httPromise(appUrl + '/ignored');
        expect(response.data).toEqual({ ignored: true });
        expect(response.headers).not.toMatchObject({
          'x-ratelimit-limit': '2',
          'x-ratelimit-remaining': '1',
          'x-ratelimit-reset': /\d+/,
        });
      });
      it('GET /ignore-user-agents', async () => {
        const response = await httPromise(appUrl + '/ignore-user-agents', 'GET', {
          'user-agent': 'throttler-test/0.0.0',
        });
        expect(response.data).toEqual({ ignored: true });
        expect(response.headers).not.toMatchObject({
          'x-ratelimit-limit': '2',
          'x-ratelimit-remaining': '1',
          'x-ratelimit-reset': /\d+/,
        });
      });
      it('GET /', async () => {
        const response = await httPromise(appUrl + '/');
        expect(response.data).toEqual({ success: true });
        expect(response.headers).toMatchObject({
          'x-ratelimit-limit': '2',
          'x-ratelimit-remaining': '1',
          'x-ratelimit-reset': /\d+/,
        });
      });
    });
    /**
     * Tests for setting `@Throttle()` at the class level and overriding at the method level
     */
    describe('LimitController', () => {
      it.each`
        method   | url          | limit
        ${'GET'} | ${''}        | ${2}
        ${'GET'} | ${'/higher'} | ${5}
      `(
        '$method $url',
        async ({ method, url, limit }: { method: 'GET'; url: string; limit: number }) => {
          for (let i = 0; i < limit; i++) {
            const response = await httPromise(appUrl + '/limit' + url, method);
            expect(response.data).toEqual({ success: true });
            expect(response.headers).toMatchObject({
              'x-ratelimit-limit': limit.toString(),
              'x-ratelimit-remaining': (limit - (i + 1)).toString(),
              'x-ratelimit-reset': /\d+/,
            });
          }
          const errRes = await httPromise(appUrl + '/limit' + url, method);
          expect(errRes.data).toMatchObject({ statusCode: 429, message: /ThrottlerException/ });
          expect(errRes.headers).toMatchObject({
            'retry-after': /\d+/,
          });
          expect(errRes.status).toBe(429);
        },
      );
    });
    /**
     * Tests for setting throttle values at the `forRoot` level
     */
    describe('DefaultController', () => {
      it('GET /default', async () => {
        const response = await httPromise(appUrl + '/default');
        expect(response.data).toEqual({ success: true });
        expect(response.headers).toMatchObject({
          'x-ratelimit-limit': '5',
          'x-ratelimit-remaining': '4',
          'x-ratelimit-reset': /\d+/,
        });
      });
    });
  });
});