Skip to content

Commit

Permalink
Merge branch 'feature/dev-container'
Browse files Browse the repository at this point in the history
  • Loading branch information
yamcodes committed Oct 9, 2023
2 parents 582f48c + 9c7f1ac commit 7eec6aa
Show file tree
Hide file tree
Showing 16 changed files with 407 additions and 36 deletions.
63 changes: 63 additions & 0 deletions .devcontainer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/javascript-node-postgres
{
"name": "Bun & Postgres",
"dockerComposeFile": "docker-compose.yml",
"service": "app",
"workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}",
// Features to add to the dev container. More info: https://containers.dev/features.
"features": {
"ghcr.io/devcontainers/features/github-cli:1": {},
"ghcr.io/devcontainers-contrib/features/zsh-plugins:0": {
"plugins": "zsh-completions zsh-autosuggestions zsh-syntax-highlighting",
"omzPlugins": "https://github.com/zsh-users/zsh-completions.git https://github.com/zsh-users/zsh-autosuggestions.git https://github.com/zsh-users/zsh-syntax-highlighting.git"
},
"ghcr.io/shyim/devcontainers-features/bun:0": {},
"ghcr.io/itsmechlark/features/postgresql:1.3.3": {}
},
"waitFor": "onCreateCommand",
"updateContentCommand": "bun i",
"postAttachCommand": {
"app": "bun dev",
"studio": "bun db:studio"
},
// "postCreateCommand": "bun db:migrate && bun db:seed",
"postCreateCommand": "./scripts/create-db.sh",
"customizations": {
"vscode": {
"extensions": [
"biomejs.biome",
"ms-azuretools.vscode-docker",
"w0o0o.bun-scripts",
"oven.bun-vscode",
"antfu.browse-lite",
"mtxr.sqltools",
"mtxr.sqltools-driver-pg",
"bierner.markdown-preview-github-styles"
],
"settings": {
"editor.tabSize": 2,
"editor.insertSpaces": true,
"terminal.integrated.defaultProfile.linux": "zsh"
}
}
},
"portsAttributes": {
"3000": {
"label": "App",
"onAutoForward": "openPreview"
},
"4983": {
"label": "Studio"
},
"5432": {
"label": "Database"
}
},
"forwardPorts": [5432,3000,4983]

// Configure tool-specific properties.
// "customizations": {},
// Needed for bun install (for access to save .lockb). More info: https://aka.ms/dev-containers-non-root.
// "remoteUser": "root"
}
1 change: 1 addition & 0 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ POSTGRES_HOST=0.0.0.0
POSTGRES_PORT=5432
JWT_SECRET=supersecretkey
JWT_ALGORITHM=HS256
APP_PORT=3000
Empty file added .gitconfig
Empty file.
14 changes: 13 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,17 @@
"editor.tabSize": 2,
"[javascript]": {
"editor.defaultFormatter": "biomejs.biome"
}
},
"sqltools.connections": [
{
"previewLimit": 50,
"server": "localhost",
"port": 5432,
"driver": "PostgreSQL",
"name": "Postgres",
"database": "medium",
"username": "postgres",
"password": "postgres"
}
]
}
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

Hey there! We're thrilled that you'd like to contribute to this project. Your help is essential for keeping it great and we truly appreciate your time and effort.

> [!WARNING]
> Before submitting your contribution, please make sure to take a moment and read through the following guidelines.
> [!IMPORTANT]
> Before submitting your contribution, please take a moment and read through the following guidelines.
## 👨‍💻 Repository Setup

Expand Down
14 changes: 10 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ The runtime is [Bun](https://bun.sh/) and the code is written in [TypeScript](ht

# Getting started

> [!NOTE]
> This project includes support for [Dev Containers](https://code.visualstudio.com/docs/remote/containers) in VSCode. If you have VSCode installed, and Docker daemon running, you can simply open the project in VSCode and click on the "_Reopen in Container_" button in the notification that pops up. This will automatically perform the steps below and open a new VSCode window with the project running inside a container ready for development.
> [!WARNING]
> **When using dev containers**: For now, you must _rebuild_ the container using `cmd+p > Dev Containers: Rebuild Container` after building the container the first time. See [#55](https://github.com/agnyz/elysia-realworld-example-app/issues/55) for details; PRs welcome.
1. **Clone and install dependencies**

```bash
Expand All @@ -31,15 +37,15 @@ The runtime is [Bun](https://bun.sh/) and the code is written in [TypeScript](ht
bun i
```

2. **Ensure Docker daemon is running and spin up the Postgres container**
2. **Ensure Docker daemon is running and spin up the Postgres+Bun container**

```bash
bun db:up
bun up
```
3. **Push the schema to the database**
3. **Migrate the schema to the database**

```bash
bun db:push
bun db:migrate
```

4. **Run the app**
Expand Down
3 changes: 2 additions & 1 deletion SUPPORT.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
This article explains where to get help with remark.
Please read through the following guidelines.

> 👉 **Note**: before participating in our community, please read our
> [!WARNING]
> Before participating in our community, please read our
> [code of conduct](CODE_OF_CONDUCT.md).
> By interacting with this repository, organization, or community you agree to
> abide by its terms.
Expand Down
6 changes: 2 additions & 4 deletions biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@
"enabled": true,
"rules": {
"recommended": true
}
},
"files": {
"maxSize": 3145728
},
"ignore": [".devcontainer*", ".vscode/**/*", "node_modules/**/*"]
}
}
22 changes: 22 additions & 0 deletions db/drop.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { db } from '@/database.providers';
import { users } from '@/users/users.schema';
import { getTableName } from 'drizzle-orm';
import { exit } from 'process';
// TODO: use react-ink

const tables = [users];

console.log('Dropping the entire database');

for (const table of tables) {
const name = getTableName(table);
console.log(`Dropping ${name}`);
await db.delete(users);
console.log(`Dropped ${name}`);
const tableResult = await db.select().from(table);
console.log(`${name} result: `, tableResult);
}

console.log('Database dropped');

exit(0);
8 changes: 4 additions & 4 deletions db/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ import { db } from '@/database.providers';
import { users } from '@/users/users.model';

const data = {
id: users.id.default,
id: 1, //do not use 'users.id.default', seed should be idempotent
email: '[email protected]',
username: 'test',
password: 'test',
bio: 'test',
image: 'test',
};
console.log('Inserting user: ', data);
await db.insert(users).values(data);
console.log('User inserted');
console.log('Upserting user: ', data);
await db.insert(users).values(data).onConflictDoNothing();
console.log('User upserted');

const userResult = await db.select().from(users);
console.log('User result: ', userResult);
Expand Down
53 changes: 40 additions & 13 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,22 +1,49 @@
version: '3.8'

services:
db:
image: postgres
restart: always
ports:
- ${POSTGRES_PORT}:5432
image: postgres:16
restart: unless-stopped
volumes:
- postgres-data:/var/lib/postgresql/data
environment:
PGUSER: ${POSTGRES_USER}
POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
- POSTGRES_DB=${POSTGRES_DB}
healthcheck:
test: ["CMD-SHELL", "pg_isready"]
test:
[
"CMD-SHELL",
"PGPASSWORD=$${POSTGRES_PASSWORD} psql -U $${POSTGRES_USER} -d $${POSTGRES_DB} -c 'SELECT 1;' || exit 1"
]
interval: 1s
timeout: 5s
retries: 10
# This allows accessing externally from "localhost" in addition to "127.0.0.1"
ports:
- ${POSTGRES_PORT}:5432

app:
image: node:20-bullseye
restart: unless-stopped

volumes:
- pgdata:/var/lib/postgresql/data
env_file:
- .env
- ..:/workspaces:cached
- ../scripts:/scripts:cached

# Overrides default command so things don't shut down after the process ends.
command: sleep infinity

# Runs app on the same network as the database container, allows "forwardPorts" in devcontainer.json function.
network_mode: service:db
# Use "forwardPorts" in **devcontainer.json** to forward an app port locally.
# (Adding the "ports" property to this file will not forward from a Codespace.)

# depends_on:
# - db
# environment:
# - POSTGRES_HOST=db # connect to the Postgres container with Docker Networking
# - POSTGRES_PORT=5432 # use internal port of Postgres container

volumes:
pgdata:
postgres-data:
17 changes: 11 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,23 @@
"start": "bun run src/main.ts",
"dev": "bun run --watch src/main.ts",
"test": "echo \"Error: no test specified\" && exit 1",
"format": "biome format --write .",
"lint": "biome lint .",
"format": "biome format --write src --no-errors-on-unmatched",
"lint": "biome lint src --no-errors-on-unmatched",
"docs": "vitepress dev docs",
"docs:build": "vitepress build docs",
"docs:preview": "vitepress preview docs",
"db:up": "./scripts/create-start-container-with-env.sh",
"up": "./scripts/create-start-container-with-env.sh",
"db:generate": "bun drizzle-kit generate:pg --config=db/config.ts",
"db:migrate": "bun run db/migrate.ts",
"db:push": "bun drizzle-kit push:pg --config=db/config.ts",
"db:seed": "bun run db/seed.ts",
"db:seed": "bun db/seed.ts",
"db:studio": "bun drizzle-kit studio --config=db/config.ts",
"db:drop": "bun db/drop.ts",
"prepare": "husky install"
},
"dependencies": {
"@elysiajs/swagger": "^0.7.3",
"commander": "^11.0.0",
"drizzle-orm": "^0.28.6",
"drizzle-typebox": "^0.1.1",
"elysia": "^0.7.15",
Expand All @@ -43,7 +45,10 @@
"module": "src/index.ts",
"type": "module",
"lint-staged": {
"*.json": "biome format --write",
"*.ts": ["biome lint --apply", "biome format --write"]
"*.json": "biome format --write --no-errors-on-unmatched",
"*.ts": [
"biome lint --apply --no-errors-on-unmatched",
"biome format --write --no-errors-on-unmatched"
]
}
}
15 changes: 15 additions & 0 deletions scripts/create-db.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/bin/bash

# Source .env file to get environment variables
source .env

# TODO: find a fix for database ('medium') creation without having to rebuild

# Run wait-for-db.sh with the sourced environment variables
# ./scripts/wait-for-db.sh db:5432 --strict --timeout=60 -- psql -h db -U ${POSTGRES_USER} -d ${POSTGRES_DB} -c 'SELECT 1;'

# TODO: find a better way to wait for database ('medium') creation than waiting 10 seconds
sleep 10

bun db:migrate
bun db:seed
Loading

0 comments on commit 7eec6aa

Please sign in to comment.