Skip to content

Commit

Permalink
TypeORM Migrations integrated
Browse files Browse the repository at this point in the history
  • Loading branch information
nikolasp committed Jan 24, 2021
1 parent b7957cb commit a8e6029
Show file tree
Hide file tree
Showing 8 changed files with 87 additions and 11 deletions.
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ DB_USERNAME=nest
DB_PASSWORD=nest
DB_HOST=db
DB_PORT=3306
DB_DATABASE=nest
DB_DATABASE=nest
DB_SYNC=false
4 changes: 3 additions & 1 deletion Dockerfile-prod
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ WORKDIR /app

ENV NODE_ENV production
COPY package.json yarn.lock ./
RUN set -x && yarn

# install dev dependencies too
RUN set -x && yarn --prod=false

COPY . .
RUN set -x && yarn run prestart:prod
Expand Down
35 changes: 28 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,38 @@ Just run already prepared bash script:
```bash
$ ./init
```
It will setup the project for you (building the Docker images, starting docker-compose stack).
It will setup the project for you (starting docker-compose stack, running migrations).
The NestJS app running in dev mode will be exposed on `http://localhost` (port 80)

For IDE autocompletion to work, run `yarn` on the host machine.

## TypeORM integrated

[TypeORM](http://typeorm.io/) gives you possibility to use next db types:
`mysql`, `postgres`, `mariadb`, `sqlite`, etc. Please look at docs for more details.
The `docker-compose` template uses `mariadb`.
## Migrations

If you don't work on a production-ready project you can always change `DB_SYNC` env variable to true so you can play with NestJS without the need to write actual migrations.

**`synchronize: true` shouldn't be used in production - otherwise, you can lose production data.**

### Create Migration
Creating new migration is relatively easy and you can use typeorm CLI for that. You can run this command to create new migration:
```bash
$ docker exec -it nest yarn migration:create -n {CreateTableUsers}
```
Migration file will be placed under `src/migrations`. For more details check the existing [1611484925515-CreateUsersTable.ts](src/migrations/1611484925515-CreateUsersTable.ts)

### Run Migrations
```bash
$ docker exec -it nest yarn migration:run
```
### Revert Migrations
```bash
$ docker exec -it nest yarn migration:revert
```

## Test

```bash
Expand All @@ -58,12 +85,6 @@ and read all environment variables from `.env` file, which is created automatica
RESTful APIs you can describe with already integrated Swagger.
To see all available endpoints visit http://localhost/api/docs

## TypeORM integrated

[TypeORM](http://typeorm.io/) gives you possibility to use next db types:
`mysql`, `postgres`, `mariadb`, `sqlite`, etc. Please look at docs for more details.
The `docker-compose` template uses `mariadb`.

## Authentication - JWT

Already preconfigured JWT authentication.
Expand Down
6 changes: 6 additions & 0 deletions init
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,9 @@ docker-compose up -d
if [ $? -ne 0 ]; then
err "Error while starting docker-compose stack."
fi

log "Run migrations: yarn migration:run"
docker exec -it nest yarn migration:run
if [ $? -ne 0 ]; then
err "Migrations failed."
fi
23 changes: 23 additions & 0 deletions ormconfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const dotenv = require('dotenv');

dotenv.config();

const {
DB_TYPE,
DB_HOST,
DB_USERNAME,
DB_PASSWORD,
DB_PORT,
DB_DATABASE,
} = process.env;

module.exports = {
type: DB_TYPE,
host: DB_HOST,
port: DB_PORT,
username: DB_USERNAME,
password: DB_PASSWORD,
database: DB_DATABASE,
migrations: [__dirname + '/src/migrations/*{.ts,.js}'],
entities: [__dirname + '/src/**/*.entity.{ts,js}'],
};
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@
"test:cov": "jest --coverage",
"test:e2e": "jest --config ./test/jest-e2e.json",
"webpack": "webpack --config webpack.config.js",
"ts-typeorm": "ts-node ./node_modules/typeorm/cli.js"
"ts-typeorm": "ts-node ./node_modules/typeorm/cli.js",
"migration:create": "typeorm migration:create -d src/migrations",
"migration:run": "yarn ts-typeorm migration:run",
"migration:revert": "yarn ts-typeorm migration:revert"
},
"dependencies": {
"@nestjs/common": "^7.6.5",
Expand Down
20 changes: 20 additions & 0 deletions src/migrations/1611484925515-CreateUsersTable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class CreateUsersTable1611484925515 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE users (
id int(11) NOT NULL AUTO_INCREMENT,
firstName varchar(255) NOT NULL,
lastName varchar(255) NOT NULL,
email varchar(255) NOT NULL,
password varchar(255) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;`,
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE IF EXISTS users;`);
}
}
2 changes: 1 addition & 1 deletion src/modules/main/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { AuthModule } from './../auth';
password: configService.get('DB_PASSWORD'),
database: configService.get('DB_DATABASE'),
entities: [__dirname + './../**/**.entity{.ts,.js}'],
synchronize: configService.isEnv('dev'),
synchronize: configService.get('DB_SYNC') === 'true',
} as TypeOrmModuleAsyncOptions;
},
}),
Expand Down

0 comments on commit a8e6029

Please sign in to comment.