my-custom-server
v0.0.6
Published
```bash $ yarn install my-custom-server ```
Downloads
6
Readme
Project setup
$ yarn install my-custom-servercopy codigo necesario
import { NestFactory } from '@nestjs/core';
import * as compression from 'compression';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { bold } from 'chalk';
import { RequestMethod, VersioningType } from '@nestjs/common';
import { NestExpressApplication } from '@nestjs/platform-express';
import { configSwagger } from './helpers/swagger.helper';
// import { GlobalValidationPipe } from 'blade-core';
import { urlencoded, json } from 'express';
/**
* Función de arranque del servidor NestJS.
* Configura varias características del servidor como compresión, CORS, versionado de API, etc.
*/
async function bootstrap() {
// Crea una instancia de la aplicación NestJS con soporte para Express
const app = await NestFactory.create<NestExpressApplication>(AppModule, {});
// Obtiene el servicio de configuración para acceder a las variables de entorno
const envService = app.get(ConfigService);
const packageJson = envService.get('packageJson');
// Configura la aplicación para manejar JSON y datos codificados en URL con límites personalizados
app.use(json({ limit: envService.get('limitRequest') }));
app.use(urlencoded({ extended: true, limit: envService.get('limitRequest') }));
// Habilita el versionado de la API mediante la URI (p. ej., `/v1/endpoint`)
app.enableVersioning({ type: VersioningType.URI });
// Habilita la compresión de respuestas HTTP para mejorar el rendimiento
app.use(compression());
// Define un prefijo global para los endpoints de la API (excluye la ruta raíz `/`)
app.setGlobalPrefix('api', {
exclude: [{ path: '/', method: RequestMethod.GET }],
});
// Habilita CORS con configuraciones específicas para orígenes permitidos y métodos HTTP
app.enableCors({
origin: envService.get('enableCors'),
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
credentials: true,
});
// Configura Swagger en entornos que no son de producción para documentación de API
if (envService.get('environment') !== 'production') {
configSwagger(app, packageJson);
}
// Define el puerto desde la configuración y arranca el servidor
const port = envService.get<number>('port');
await app.listen(port, '0.0.0.0').then(async () => {
console.info(
bold.blue(
`🚀 "${packageJson.name}", version:"${packageJson.version}" API is listening ON PORT`,
`${await app.getUrl()}/api`,
),
);
});
}creas una carpeta helpers y dentro de ella lo siguiente
nombre del archivo swagger .helper.ts
import { INestApplication} from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
export const configSwagger = (app: INestApplication, packageJson: any) => {
const config = new DocumentBuilder()
.setTitle(packageJson.system)
.setVersion(packageJson.version)
.setDescription(packageJson.description)
.setContact(packageJson.contact.name, '', packageJson.contact.email)
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document, {
customSiteTitle: packageJson.system,
customfavIcon: '../assets/images/favicon.ico',
customCss: `
.swagger-ui .topbar { display: none; }
.swagger-ui .info { margin: 20px 0;}
.swagger-ui .info hgroup.main { margin: 0 0 0;}
.title span { display: block; }
`,
});
};
creas una carpeta config y dentro de ella lo siguiente
nombre del archivo configuration.ts
import { join } from 'path';
export default () => {
const locatePackagejson = process.cwd();
let pm2 = false;
if (locatePackagejson.includes('dist')) {
pm2 = true;
}
return {
packageJson: require(
join(process.cwd(), pm2 ? '../package.json' : 'package.json'),
),
port: parseInt(process.env.ENV_PORT, 10) || 8001,
secretKey: process.env.SECRET_KEY,
tokenExpiresIn: process.env.TOKEN_EXPIRES_IN || '1d',
enableCors:
process.env.ENVIRONMENT === 'production'
? process.env.CORS_ORIGIN.split(',')
: '*',
};
};
yarn installpor el momento solo dentro de app.module.ts la siguiente configuracion y lo demas funcionara
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MongooseModule } from '@nestjs/mongoose';
import { ConfigModule } from '@nestjs/config';
import { UsersModule } from 'my-custom-server';
import configuration from './config/configuration';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [configuration],
}),
MongooseModule.forRoot(process.env.MONGODB_URI='su conexion a base de datos'),
UsersModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
// Llama a la función de arranque para iniciar la aplicación bootstrap();
# unit tests
$ yarn run test
# e2e tests
$ yarn run test:e2e
# test coverage
$ yarn run test:covResources
Check out a few resources that may come in handy when working with NestJS:
- Visit the NestJS Documentation to learn more about the framework.
- For questions and support, please visit our Discord channel.
- To dive deeper and get more hands-on experience, check out our official video courses.
- Visualize your application graph and interact with the NestJS application in real-time using NestJS Devtools.
- Need help with your project (part-time to full-time)? Check out our official enterprise support.
- To stay in the loop and get updates, follow us on X and LinkedIn.
- Looking for a job, or have a job to offer? Check out our official Jobs board.
Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please read more here.
Stay in touch
- Author - Kamil Myśliwiec
- Website - https://nestjs.com
- Twitter - @nestframework
License
Nest is MIT licensed.
