@nestjs/platform-express#ExpressAdapter TypeScript Examples
The following examples show how to use
@nestjs/platform-express#ExpressAdapter.
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: index.ts From aws-nestjs-starter with The Unlicense | 6 votes |
bootstrapServer = async (): Promise<Handler> => {
const expressApp = express();
const app = await NestFactory.create(
AppModule,
new ExpressAdapter(expressApp),
);
app.useGlobalPipes(new ValidationPipe({ forbidUnknownValues: true }));
app.enableCors();
await app.init();
return serverlessExpress({
app: expressApp,
});
}
Example #2
Source File: lambda-main.ts From mamori-i-japan-api with BSD 2-Clause "Simplified" License | 6 votes |
bootstrapServer = async (): Promise<Server> => {
const expressApp = express()
const adapter = new ExpressAdapter(expressApp)
const app = await NestFactory.create(AppModule, adapter, {
logger: false,
})
app.useLogger(new AppLogger())
app.use(RequestIdMiddleware)
app.use(eventContext())
app.enableCors()
await app.init()
return createServer(expressApp)
}
Example #3
Source File: lambda-swagger.ts From mamori-i-japan-api with BSD 2-Clause "Simplified" License | 6 votes |
bootstrapServer = async (): Promise<Server> => {
const expressApp = express()
const adapter = new ExpressAdapter(expressApp)
const app = await NestFactory.create(AppModule, adapter, {
logger: false,
})
app.useLogger(new AppLogger())
app.use(eventContext())
app.enableCors()
const options = new DocumentBuilder()
.setTitle('mamori-i-japan-api')
.setDescription('Swagger UI for mamori-i-japan-api API')
.setVersion('1.0')
.addBearerAuth()
.build()
const document = SwaggerModule.createDocument(app, options)
SwaggerModule.setup('swagger', app, document)
await app.init()
return createServer(expressApp)
}
Example #4
Source File: main.ts From bank-server with MIT License | 6 votes |
async function bootstrap(): Promise<void> {
initializeTransactionalContext();
patchTypeORMRepositoryWithBaseRepository();
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
new ExpressAdapter(),
{ cors: true },
);
app.enable('trust proxy');
app.use(helmet());
app.use(RateLimit({ windowMs: 15 * 60 * 1000, max: 200 }));
app.use(compression());
app.use(morgan('combined'));
app.setGlobalPrefix('bank');
const reflector = app.get(Reflector);
app.useGlobalInterceptors(new ClassSerializerInterceptor(reflector));
app.useGlobalFilters(
new HttpExceptionFilter(reflector),
new QueryFailedFilter(reflector),
);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
transform: true,
dismissDefaultMessages: true,
validationError: { target: false },
}),
);
setupSwagger(app);
const configService = app.get(ConfigService);
await app.listen(configService.get('PORT'));
}
Example #5
Source File: main-firebase.ts From edu-server with MIT License | 5 votes |
async function createFunction(expressInstance) {
const app = await NestFactory.create(
AppModule,
new ExpressAdapter(expressInstance),
);
await app.init();
}
Example #6
Source File: main.ts From ironfish-api with Mozilla Public License 2.0 | 5 votes |
async function bootstrap(): Promise<void> {
const server = express();
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
new ExpressAdapter(server),
);
const config = app.get(ApiConfigService);
const logger = app.get(LoggerService);
const defaultOrigins = [
config.get<string>('BLOCK_EXPLORER_URL'),
config.get<string>('INCENTIVIZED_TESTNET_URL'),
];
const enabledOrigins = config.isStaging()
? [
...defaultOrigins,
/localhost/,
/block-explorer.*\.vercel\.app/,
/website-testnet.*\.vercel\.app/,
]
: defaultOrigins;
app.enableCors({
origin: enabledOrigins,
methods: 'GET, POST, PUT, OPTIONS',
allowedHeaders: ['Content-Type', 'Accept', 'Authorization'],
credentials: true,
});
app.use(compression());
app.use(helmet());
app.use(json({ limit: '10mb' }));
const swaggerConfig = new DocumentBuilder()
.setTitle('Iron Fish API')
.setDescription('The Rest API to enable public access to Iron Fish data')
.setVersion('')
.build();
const document = SwaggerModule.createDocument(app, swaggerConfig);
SwaggerModule.setup('docs', app, document, {
customSiteTitle: 'Iron Fish API Documentation',
});
await app.init();
const port = config.get<number>('PORT');
logger.info(`Starting API on PORT ${port}`);
const httpServer = http.createServer(server).listen(port);
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => {
httpServer.close();
void app.close();
});
}
}
Example #7
Source File: main.ts From nestjs-throttler-storage-redis with MIT License | 5 votes |
async function bootstrap() {
const app = await NestFactory.create(
AppModule,
new ExpressAdapter(),
// new FastifyAdapter(),
);
await app.listen(3000);
}
Example #8
Source File: controller.e2e-spec.ts From nestjs-throttler-storage-redis with MIT License | 4 votes |
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+/,
});
});
});
});
});