Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Setup Database Connect & swagger #2

Merged
merged 11 commits into from
Feb 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
NODE_ENV=production

DB_HOST=127.0.0.1
DB_PORT=3306
DB_USERNAME=cophr
DB_PASSWORD=secret
DB_DATABASE=cophr
DB_TIMEZONE="+08:00"

APP_SWAGGER_Title="NestJS-Board API"
APP_SWAGGER_Description="This is NestJS-Board API documentation."
APP_SWAGGER_Version="0.0.1"
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ lerna-debug.log*

# OS
.DS_Store
.env

# Tests
/coverage
Expand Down
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,25 @@ $ npm run test:e2e
$ npm run test:cov
```

## Migration

```bash
# build and according to dist/**/*.entity.js difference between previous and now to generate sql queries
$ yarn migration:generate src/database/migrations/{THIS_migration_DO}

# build and create new empty migration which custom sql queries
$ yarn migration:create src/database/migrations/{THIS_migration_DO}

# build and run with sql queries to update a database
$ yarn migration:run

# build and view current status which database migration version
$ yarn migration:show

# build and revert database to previous version
$ yarn migration:revert
```

## 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](https://docs.nestjs.com/support).
Expand Down
18 changes: 17 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@
"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",
"typeorm": "npm run build && npx typeorm -d ./dist/config/data-source.js",
"migration:generate": "npm run typeorm -- migration:generate",
"migration:create": "npm run typeorm -- migration:create",
"migration:run": "npm run typeorm -- migration:run",
"migration:show": "npm run typeorm -- migration:show",
"migration:revert": "npm run typeorm -- migration:revert",
"prepare": "husky install"
},
"lint-staged": {
Expand All @@ -27,11 +33,21 @@
},
"dependencies": {
"@nestjs/common": "^9.0.0",
"@nestjs/config": "^2.2.0",
"@nestjs/core": "^9.0.0",
"@nestjs/mapped-types": "*",
"@nestjs/platform-express": "^9.0.0",
"@nestjs/swagger": "^6.1.4",
"@nestjs/typeorm": "^9.0.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"dotenv": "^16.0.3",
"mysql2": "^2.3.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0"
"rxjs": "^7.2.0",
"swagger-ui-express": "^4.6.0",
"typeorm": "^0.3.11"
},
"devDependencies": {
"@commitlint/cli": "^17.3.0",
Expand Down
11 changes: 10 additions & 1 deletion src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { TypeOrmModule } from "@nestjs/typeorm";

import { AppController } from "./app.controller";
import { AppService } from "./app.service";
import { dataSourceOptions } from "./config/data-source";
import { validate } from "./config/env.validation";

@Module({
imports: [],
imports: [
ConfigModule.forRoot({
validate,
}),
TypeOrmModule.forRoot(dataSourceOptions),
],
controllers: [AppController],
providers: [AppService],
})
Expand Down
23 changes: 23 additions & 0 deletions src/config/data-source.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as dotenv from "dotenv";
import { DataSource, DataSourceOptions } from "typeorm";

dotenv.config();
export const dataSourceOptions: DataSourceOptions = {
type: "mysql",
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT, 10),
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
timezone: process.env.DB_TIMEZONE,
entities: [__dirname + "/../**/*.entity.js"],
migrations: [__dirname + "/../database/migrations/*.js"],
extra: {
charset: "utf8mb4_unicode_ci",
},
synchronize: false,
logging: false,
};

const dataSource = new DataSource(dataSourceOptions);
export default dataSource;
58 changes: 58 additions & 0 deletions src/config/env.validation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { plainToInstance } from "class-transformer";
import {
IsEnum,
IsNotEmpty,
IsNumber,
IsString,
validateSync,
} from "class-validator";

export enum Environment {
Development = "development",
Production = "production",
Test = "test",
Provision = "provision",
}

class EnvironmentVariables {
@IsEnum(Environment)
NODE_ENV: Environment = Environment.Production;

@IsString()
@IsNotEmpty()
DB_HOST: string;

@IsNumber()
@IsNotEmpty()
DB_PORT: number;

@IsString()
@IsNotEmpty()
DB_USERNAME: string;

@IsString()
@IsNotEmpty()
DB_PASSWORD: string;

@IsString()
@IsNotEmpty()
DB_DATABASE: string;

@IsString()
@IsNotEmpty()
DB_TIMEZONE: string;
}

export function validate(config: Record<string, unknown>) {
const validatedConfig = plainToInstance(EnvironmentVariables, config, {
enableImplicitConversion: true,
});
const errors = validateSync(validatedConfig, {
skipMissingProperties: false,
});

if (errors.length > 0) {
throw new Error(errors.toString());
}
return validatedConfig;
}
15 changes: 15 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,24 @@
import { INestApplication } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";

import { AppModule } from "./app.module";

async function bootstrap() {
const app = await NestFactory.create(AppModule);
setupSwagger(app);
await app.listen(3000);
}

function setupSwagger(app: INestApplication) {
const builder = new DocumentBuilder();
const config = builder
.setTitle(process.env.APP_SWAGGER_Title)
.setDescription(process.env.APP_SWAGGER_Description)
.setVersion(process.env.APP_SWAGGER_Version)
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup("api", app, document);
}

bootstrap();
Loading