Skip to content

Commit

Permalink
Merge pull request #9 from Brints/feat/environment_configurations
Browse files Browse the repository at this point in the history
feat: environment configurations
  • Loading branch information
aniebietafia authored Aug 31, 2024
2 parents 80220c9 + f4cd2ef commit 41045d3
Show file tree
Hide file tree
Showing 8 changed files with 237 additions and 61 deletions.
18 changes: 12 additions & 6 deletions brints-estate-api/package.json
Original file line number Diff line number Diff line change
@@ -1,25 +1,26 @@
{
"name": "brints-estate-api",
"version": "0.0.1",
"description": "",
"description": "A Real Estate API",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"start:dev": "NODE_ENV=development nest start --watch",
"start:debug": "NODE_ENV=development nest start --debug --watch",
"start:prod": "NODE_ENV=production node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test": "NODE_ENV=development jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@hapi/joi": "^17.1.1",
"@nestjs/common": "^10.4.1",
"@nestjs/config": "^3.2.3",
"@nestjs/core": "^10.4.1",
Expand All @@ -29,6 +30,7 @@
"@nestjs/typeorm": "^10.0.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"joi": "^17.13.3",
"pg": "^8.12.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
Expand All @@ -41,6 +43,7 @@
"@nestjs/schematics": "^10.1.4",
"@nestjs/testing": "^10.4.1",
"@types/express": "^4.17.21",
"@types/hapi__joi": "^17.1.14",
"@types/jest": "^29.5.12",
"@types/node": "^22.5.0",
"@types/pg": "^8",
Expand All @@ -67,7 +70,10 @@
"json",
"ts"
],
"rootDir": "src",
"rootDir": "./",
"modulePaths": [
"<rootDir>"
],
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
Expand Down
38 changes: 23 additions & 15 deletions brints-estate-api/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,37 @@
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';

import { AuthModule } from './auth/auth.module';
import { UsersModule } from './users/users.module';
// import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from './auth/auth.module';
import { environmentValidationSchema } from './config/environment.validation';

@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: !process.env.NODE_ENV
? '.env'
: `.env.${process.env.NODE_ENV}`,
validationSchema: environmentValidationSchema,
}),
TypeOrmModule.forRootAsync({
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
type: 'postgres',
host: configService.get('DB_HOST'),
port: configService.get('DB_PORT'),
username: configService.get('DB_USER'),
password: configService.get('DB_PASSWORD'),
database: configService.get('DB_NAME'),
autoLoadEntities: process.env.NODE_ENV === 'development',
synchronize: process.env.NODE_ENV === 'development',
entities: [__dirname + '/**/*.entity{.ts,.js}'],
// entities: [User, UserAuth],
}),
}),
AuthModule,
UsersModule,
// TypeOrmModule.forRootAsync({
// useFactory: () => ({
// type: 'postgres',
// host: 'localhost',
// port: 5432,
// username: 'postgres',
// password: 'postgres',
// database: 'brints-estate-backend',
// synchronize: true,
// autoLoadEntities: true,
// })
// })
],
})
export class AppModule {}
22 changes: 22 additions & 0 deletions brints-estate-api/src/config/config.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class AppConfigService {
constructor(private readonly configService: ConfigService) {}

getConfig() {
return {
database: {
dbHost: this.configService.get<string>('DB_HOST') as string,
dbPort: this.configService.get<number>('DB_PORT') as number,
dbUser: this.configService.get<string>('DB_USER') as string,
dbPassword: this.configService.get<string>('DB_PASSWORD') as string,
dbName: this.configService.get<string>('DB_NAME') as string,
},
app: {
port: this.configService.get<number>('APP_PORT') as number,
},
};
}
}
21 changes: 21 additions & 0 deletions brints-estate-api/src/config/config.swagger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { INestApplication } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

export function swaggerInitializer(app: INestApplication<any>) {
const config = new DocumentBuilder()
.setTitle('Brints Estate API')
.setDescription(
'The modern day Real Estate API simplifying the way we buy and sell properties',
)
.addServer('http://localhost:3001', 'Development Server')
.addServer('https://brints-estate-api.herokuapp.com', 'Production Server')
.setTermsOfService('http://localhost:3001/terms')
.setLicense(
'MIT',
'https://github.com/Brints/nestjs-brints-group-estate/blob/main/LICENSE',
)
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api-docs', app, document);
}
28 changes: 28 additions & 0 deletions brints-estate-api/src/config/environment.validation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// import Joi from '@hapi/joi';
import * as Joi from 'joi';

// export const environmentValidationSchema = Joi.object({
// APP_PORT: Joi.number().default(8000),
// DB_HOST: Joi.string().required(),
// DB_PORT: Joi.number().default(5432),
// DB_USER: Joi.string().required(),
// DB_PASSWORD: Joi.string().required(),
// DB_NAME: Joi.string().required(),
// NODE_ENV: Joi.string()
// .required()
// .valid('development', 'production', 'test')
// .default('development'),
// });

export const environmentValidationSchema = Joi.object({
APP_PORT: Joi.number().port().default(8000),
DB_HOST: Joi.string().required(),
DB_PORT: Joi.number().port().default(5432),
DB_USER: Joi.string().required(),
DB_PASSWORD: Joi.string().required(),
DB_NAME: Joi.string().required(),
NODE_ENV: Joi.string()
.required()
.valid('development', 'production', 'test', 'staging')
.default('development'),
});
40 changes: 25 additions & 15 deletions brints-estate-api/src/database/data-source.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,32 @@
import { DataSource } from 'typeorm';

import { User } from 'src/users/entities/user.entity';
import { UserAuth } from 'src/users/entities/userAuth.entity';
import { DataSource } from 'typeorm';

const AppDataSource = new DataSource({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'postgres',
database: 'brints-estate-backend',
synchronize: true,
entities: [User, UserAuth],
// entities: [__dirname + '/**/*.entity{.ts,.js}'],
});
const isDevelopment = process.env.NODE_ENV === 'development';

interface DataSourceConfig {
dbHost: string;
dbPort: number;
dbUser: string;
dbPassword: string;
dbName: string;
}

export function createDataSource(config: DataSourceConfig) {
return new DataSource({
type: 'postgres',
host: config.dbHost,
port: config.dbPort,
username: config.dbUser,
password: config.dbPassword,
database: config.dbName,
synchronize: isDevelopment,
entities: [User, UserAuth],
});
}

export async function initializeDataSource() {
export async function initializeDataSource(AppDataSource: DataSource) {
try {
if (!AppDataSource.isInitialized) {
await AppDataSource.initialize();
Expand All @@ -25,5 +37,3 @@ export async function initializeDataSource() {
throw error;
}
}

export default AppDataSource;
33 changes: 8 additions & 25 deletions brints-estate-api/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,20 @@
import { NestFactory } from '@nestjs/core';
import { ConfigService } from '@nestjs/config';
import { Logger } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

import { AppModule } from './app.module';
import { initializeDataSource } from './database/data-source';
import { swaggerInitializer } from './config/config.swagger';

async function bootstrap() {
await initializeDataSource();
const app = await NestFactory.create(AppModule);
const configService = new ConfigService();

const port = configService.get('APP_PORT');
const logger = new Logger();
const app = await NestFactory.create(AppModule);

/**
* Swagger configuration
*/
const config = new DocumentBuilder()
.setTitle('Brints Estate API')
.setDescription(
'The modern day Real Estate API simplifying the way we buy and sell properties',
)
.addServer('http://localhost:3001', 'Development Server')
.addServer('https://brints-estate-api.herokuapp.com', 'Production Server')
.setTermsOfService('http://localhost:3001/terms')
.setLicense(
'MIT',
'https://github.com/Brints/nestjs-brints-group-estate/blob/main/LICENSE',
)
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api-docs', app, document);
swaggerInitializer(app);

await app.listen(3001);
logger.log('Application started on http://localhost:3001');
await app.listen(port);
logger.log(`Application is running on ${await app.getUrl()}`);
}
bootstrap();
Loading

0 comments on commit 41045d3

Please sign in to comment.