0.0.15 • Published 4 months ago
config-core-nest v0.0.15
Configuracion de proyecto
Propiedades Obligatorias en Package.json
{
"name": "Nombre del sistema para el packageJson",
"system": "Nombre del sistema para identificarlo por devs y clientes",
"version": "0.0.1",
"description": "Descripcion del sistemaa",
"author": "blade-liger",
"contact": {
"name": "Jose David Mamani Figueroa",
"email": "j.david.figueroa.dev@gmail.com"
},
}
Configuracion .prettierrc
{
"tabWidth": 2,
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"quoteProps": "as-needed",
"bracketSpacing": true,
"useTabs": false,
"sortAttributes": false,
"jsxBracketSameLine": false,
"arrowParens": "always",
"endOfLine": "auto",
"vueIndentScriptAndStyle": true,
"printWidth": 80
}
Configuracion .prettierignore
package.json
Configuracion .eslintrc o eslint.config.mjs
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-floating-promises': 'off',
'@typescript-eslint/no-unsafe-argument': 'off',
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-var-requires': 'off',
'@typescript-eslint/no-unsafe-assignment': 'off',
'@typescript-eslint/no-require-imports': 'off',
'@typescript-eslint/no-unsafe-member-access': 'off',
'@typescript-eslint/no-unsafe-return': 'off',
'@typescript-eslint/no-unsafe-call': 'off',
},
};
Agregar Icono para el proyecto
Crear directorio y el archivo favicon.ico
PROYECTO/src/assets/images/favicon.ico
Configurar archivo nest-cli.json
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"assets": [
{
"include": "assets/**/*",
"outDir": "dist/assets"
}
],
"watchAssets": true,
"deleteOutDir": true
}
}
Configuracion Inicial Main.ts
import { NestFactory } from '@nestjs/core';
import { ConfigService } from '@nestjs/config';
import { RequestMethod, VersioningType } from '@nestjs/common';
import { NestExpressApplication } from '@nestjs/platform-express';
import { GlobalValidationPipe, configSwagger } from 'config-core-nest';
import { urlencoded, json } from 'express';
import * as compression from 'compression';
import { AppModule } from './app.module';
import { bold } from 'chalk';
import * as path from 'path';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
const envService = app.get(ConfigService);
const packageJson = envService.get('packageJson');
app.use(json({ limit: envService.get('limitRequest') }));
app.use(
urlencoded({ extended: true, limit: envService.get('limitRequest') }),
);
app.enableVersioning({ type: VersioningType.URI });
app.use(compression());
app.setGlobalPrefix('api', {
exclude: [{ path: '/', method: RequestMethod.GET }],
});
app.useGlobalPipes(new GlobalValidationPipe());
app.enableCors({
origin: envService.get('enableCors'),
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
credentials: true,
});
if (envService.get('environment') !== 'production')
configSwagger(
app,
packageJson,
path.join(__dirname, '/assets/images/favicon.ico'),
);
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`,
),
);
});
}
bootstrap();
Configuracion AppModule
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from '@nestjs/config';
import configuration from './config/configuration';
import { GlobalExceptionFilter, ResponseInterceptor } from 'config-core-nest';
import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [configuration],
}),
],
controllers: [AppController],
providers: [
AppService,
{
provide: APP_FILTER,
useClass: GlobalExceptionFilter,
},
{
provide: APP_INTERCEPTOR,
useClass: ResponseInterceptor,
},
],
})
export class AppModule {}
archivo de configuracion en carpeta /src/config/configuration.ts
import { configurationNest } from 'config-core-nest';
import { join } from 'path';
export default () => {
const locatePackagejson = process.cwd();
let pm2 = false;
if (locatePackagejson.includes('dist')) {
pm2 = true;
}
const pathPackageJson = require(join(process.cwd(), pm2 ? '../package.json' : 'package.json'));
return {
...configurationNest(pathPackageJson),
};
};
variables de entorno Obligatorias
ENVIRONMENT solo debe ser development o production
ENV_PORT=3300
ENVIRONMENT=development
LIMIT_REQUESTS=50mb
CORS_ORIGIN=*
Configuracion del archivo AppService y AppController
AppController:
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getPing() {
return this.appService.getPing();
}
}
AppService:
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class AppService {
constructor(private readonly configService: ConfigService) {}
getPing() {
return {
version: this.configService.get('packageJson').version,
system: this.configService.get('packageJson').system,
description: this.configService.get('packageJson').description,
};
}
}