CRUD Application with TypeScript & PostgreSQL
Concepts of CRUD App
Github Repository
Our CRUD APP Components:
- NodeJS
- ExpressJS
- TypeORM
- PostgreSQL
- Postgres installation with Docker
Init Package.json
yarn init -y
Install Express
yarn add express
Install TypeScript
yarn add typescript ts-node-dev @types/express -D
Init TypeScript
yarn tsc — init
tsconfig.json
“target”: “es2021”,
1. Express
import express from “express”;
const app = express();
app.listen(3000, ()=>console.log(“Server is running”));
2. TypeORM
# Installation
yarn add typeorm reflect-metadata pg
- Install the npm package:
yarn install typeorm --save
- You need to install
reflect-metadata
shim: yarn install reflect-metadata --save
- and import it somewhere in the global place of your app (for example in
app.ts
): import "reflect-metadata";
- You may need to install node typings:
npm install @types/node --save-dev
- Install a database drive
- for PostgreSQL or CockroachDB
yarn install pg --save
# Using environment variables
Create .env
or ormconfig.env
in the project root (near package.json
). It should have the following content:
TYPEORM_CONNECTION = mysql
TYPEORM_HOST = localhost
TYPEORM_USERNAME = root
TYPEORM_PASSWORD = admin
TYPEORM_DATABASE = test
TYPEORM_PORT = 3000
TYPEORM_SYNCHRONIZE = true
TYPEORM_LOGGING = true
TYPEORM_ENTITIES = entity/*.js,modules/**/entity/*.js
ist of available env variables you can set:
- TYPEORM_CACHE
- TYPEORM_CACHE_ALWAYS_ENABLED
- TYPEORM_CACHE_DURATION
- TYPEORM_CACHE_OPTIONS
- TYPEORM_CONNECTION
- TYPEORM_DATABASE
- TYPEORM_DEBUG
- TYPEORM_DRIVER_EXTRA
- TYPEORM_DROP_SCHEMA
- TYPEORM_ENTITIES
- TYPEORM_ENTITIES_DIR
- TYPEORM_ENTITY_PREFIX
- TYPEORM_HOST
- TYPEORM_LOGGER
- TYPEORM_LOGGING
- TYPEORM_MAX_QUERY_EXECUTION_TIME
- TYPEORM_MIGRATIONS
- TYPEORM_MIGRATIONS_DIR
- TYPEORM_MIGRATIONS_RUN
- TYPEORM_MIGRATIONS_TABLE_NAME
- TYPEORM_PASSWORD
- TYPEORM_PORT
- TYPEORM_SCHEMA
- TYPEORM_SID
- TYPEORM_SUBSCRIBERS
- TYPEORM_SUBSCRIBERS_DIR
- TYPEORM_SYNCHRONIZE
- TYPEORM_URL
- TYPEORM_USERNAME
- TYPEORM_UUID_EXTENSION
.env
TYPEORM_CONNECTION = postgres
TYPEORM_HOST = localhost
TYPEORM_USERNAME = admin
TYPEORM_PASSWORD = admin
TYPEORM_DATABASE = code_drops_crud
TYPEORM_PORT = 5432
TYPEORM_MIGRATIONS = src/database/migrations/*.ts
TYPEORM_MIGRATIONS_DIR = src/database/migrations
docker run — name postgres -e POSTGRES_PASSWORD=admin -p 5432:5432 -d postgres
TypeORM Migrations
Migrations Commands
yarn typeorm migration:create -n CreateCategories
yarn typeorm migration:run
yarn typeorm migration:revert
Migration Videos
yarn typeorm migration:create -n CreateVideos
UUID
yarn add uuid
yarn add @types/uuid -D
Create Video
5. Postgres installation with Docker
docker pull postgresdocker run --name postgresql -e POSTGRES_PASSWORD=admin -p 5432:5432 -d postgres
❯ docker run -d --name postgresql-dev -e POSTGRESQL_USERNAME=postgres -e POSTGRESQL_PASSWORD=docker -e POSTGRESQL_DATABASE=gobarber -p 5432:5432 bitnami/postgresql:latest