Skip to content
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
518 changes: 517 additions & 1 deletion package-lock.json

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions packages/chess-app-server/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
DB_HOST=localhost
DB_PORT=5434
POSTGRES_USER=postgres
POSTGRES_DB=chess
POSTGRES_PASSWORD=postgres
1 change: 1 addition & 0 deletions packages/chess-app-server/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
db/db-data
6 changes: 6 additions & 0 deletions packages/chess-app-server/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"printWidth": 100,
"semi": false,
"singleQuote": true,
"trailingComma": "none"
}
16 changes: 16 additions & 0 deletions packages/chess-app-server/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
FROM node:16.13

WORKDIR /app

COPY package.json .
COPY package-lock.json* ./

RUN npm install

COPY . .

# Expose the port the app runs on
EXPOSE 4000

# Command to run the application
CMD ["npm", "run", "start"]
18 changes: 18 additions & 0 deletions packages/chess-app-server/db/db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import pgPromise from "pg-promise";
import dotenv from "dotenv";

dotenv.config();

const pgp = pgPromise();
const connectionConfig = {
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT || "", 10),
database: process.env.POSTGRES_DB,
user: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
schema: "public",
};

const db = pgp(connectionConfig);

export { db };
9 changes: 9 additions & 0 deletions packages/chess-app-server/db/db_schema.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
CREATE TABLE IF NOT EXISTS
"Games" (
"id" VARCHAR(70) NOT NULL PRIMARY KEY,
"gameId" VARCHAR(66),
"firstPlayerPubKey" VARCHAR(66),
"secondPlayerPubKey" VARCHAR(66),
"firstPlayerHash" VARCHAR(66),
"secondPlayerHash" VARCHAR(66)
);
29 changes: 29 additions & 0 deletions packages/chess-app-server/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
version: "3"
services:
express-app:
env_file: .env
environment:
- DB_HOST=postgres
- DB_PORT=5432
build: .
image: chess-app-server
volumes:
- ./src:/app/src
ports:
- "4000:4000"
networks:
- express-app
depends_on:
- postgres
postgres:
image: postgres
env_file: .env
ports:
- "5434:5432"
volumes:
- ./db/db-data:/var/lib/postgresql/data
- ./db/db_schema.sql:/docker-entrypoint-initdb.d/db_schema.sql
networks:
- express-app
networks:
express-app: null
37 changes: 37 additions & 0 deletions packages/chess-app-server/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "@bitcoin-computer/chess-app-server",
"version": "0.22.0-beta.0",
"type": "module",
"private": true,
"scripts": {
"start:dev": "nodemon --exec npm run start -- --ext ts",
"start": "node --loader ts-node/esm.mjs -r tsconfig-paths/register src/app.ts",
"migrate": "migrate up",
"rollback": "migrate down",
"create-migration": "migrate create",
"lint": "tslint -p tsconfig.json --fix",
"start-postgres": "docker-compose up postgres",
"up": "docker-compose up",
"build-docker": "docker build -t chess-app-server ."
},
"dependencies": {
"@types/cors": "^2.8.17",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.18.2",
"pg-promise": "^11.5.4",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"uuid": "^9.0.1"
},
"devDependencies": {
"@types/express": "^5.0.0",
"@types/node": "^20.11.20",
"@types/pg-promise": "^5.4.3",
"@types/uuid": "9.0.8",
"migrate": "^2.1.0",
"nodemon": "^3.1.0",
"tslint": "^6.1.3",
"typescript": "^5.3.3"
}
}
50 changes: 50 additions & 0 deletions packages/chess-app-server/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import express, { Request, Response } from 'express'
import { v4 as uuidv4 } from 'uuid'
import { db } from '../db/db.js'
import cors from 'cors'

const app = express()
const PORT = 4000

app.use(cors())
app.use(express.json())

app.get('/games/:gameId', async (req: Request, res: Response) => {
try {
const gameId = req.params.gameId

const data = await db.query(`SELECT * FROM "Games" WHERE "gameId" = $1`, [gameId])

if (data) {
res.json(data)
} else {
res.status(404).json({ message: 'Data not found' })
}
} catch (error) {
console.error('Error:', error)
res.status(500).json({ error: 'Internal server error' })
}
})

app.post('/games', async (req, res) => {
try {
const { gameId, firstPlayerPubKey, secondPlayerPubKey } = req.body

// You can perform validation here before updating the data
const id = uuidv4()

await db.none(
`INSERT INTO "Games" (id, "gameId", "firstPlayerPubKey", "secondPlayerPubKey", "firstPlayerHash", "secondPlayerHash") VALUES ($1, $2, $3, $4, $5, $6);`,
[id, gameId, firstPlayerPubKey, secondPlayerPubKey, 'hash1', 'hash2']
)

res.status(201).json({ message: 'Game added successfully' })
} catch (error) {
console.error('Error:', error)
res.status(500).json({ error: 'Internal server error' })
}
})

app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`)
})
14 changes: 14 additions & 0 deletions packages/chess-app-server/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES6",
"module": "ESNext",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"moduleResolution": "node",
"baseUrl": "./",
"paths": {
"*": ["src/*"]
}
}
}
1 change: 1 addition & 0 deletions packages/chess-app/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
VITE_CHAIN=LTC
VITE_NETWORK=regtest
VITE_URL=http://127.0.0.1:1031
VITE_API_BASE_URL=http://127.0.0.1:4000

# Application Port
VITE_PORT=1032
Expand Down
28 changes: 9 additions & 19 deletions packages/chess-app/src/components/CreateNewGame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ComputerContext, Modal, UtilsContext } from "@bitcoin-computer/componen
import { Link } from "react-router-dom"
import { Computer } from "@bitcoin-computer/lib"
import { VITE_CHESS_GAME_MOD_SPEC } from "../constants/modSpecs"
import { createGame } from "../services/game.service"

function SuccessContent(id: string) {
return (
Expand Down Expand Up @@ -66,7 +67,6 @@ function MintForm(props: {
}) {
const { computer, setSuccessRev, setErrorMsg } = props
const [name, setName] = useState("")
const [color, setColor] = useState("black")
const [secondPlayerPublicKey, setSecondPlayerPublicKey] = useState("")
const [secondPlayerUserName, setSecondPlayerUserName] = useState("")
const { showLoader } = UtilsContext.useUtilsComponents()
Expand All @@ -75,17 +75,19 @@ function MintForm(props: {
e.preventDefault()
try {
showLoader(true)
console.log(
`new ChessGame("${color}", "${computer.getPublicKey()}", "${secondPlayerPublicKey}", "${name}", "${secondPlayerUserName}")`
)
const { tx, effect }: any = await computer.encode({
exp: `new ChessGame("${color}", "${computer.getPublicKey()}", "${secondPlayerPublicKey}", "${name}", "${secondPlayerUserName}")`,
exp: `new ChessGame("white", "${computer.getPublicKey()}", "${secondPlayerPublicKey}", "${name}", "${secondPlayerUserName}")`,
mod: VITE_CHESS_GAME_MOD_SPEC
})

const data = await computer.broadcast(tx)
console.log(data, effect)
await computer.broadcast(tx)
setSuccessRev(effect.res?._id)
await createGame({
gameId: effect.res?._id,
firstPlayerPubKey: computer.getPublicKey(),
secondPlayerPubKey: secondPlayerPublicKey
})

showLoader(false)
Modal.showModal("success-modal")
} catch (err) {
Expand Down Expand Up @@ -139,18 +141,6 @@ function MintForm(props: {
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
/>
</div>
<label className="block mb-2 text-sm font-medium text-gray-900 dark:text-white">
Select your color
</label>
<select
id="firstPlayerColor"
value={color}
onChange={(e) => setColor(e.target.value)}
className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
>
<option value={"black"}>Black</option>
<option value={"white"}>White</option>
</select>
</div>
<button
type="submit"
Expand Down
34 changes: 34 additions & 0 deletions packages/chess-app/src/services/game.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import axios from "axios"

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL

export interface Game {
id: string
gameId: string
firstPlayerPubKey: string
secondPlayerPubKey: string
firstPlayerHash?: string
secondPlayerHash?: string
}

export const getGame = async (gameId: string): Promise<Game | null> => {
try {
const response = await axios.get<Game>(`${API_BASE_URL}/games/${gameId}`)
return response.data
} catch (error: any) {
console.error("Error fetching game:", error)
if (error.response && error.response.status === 404) {
return null
}
throw error
}
}

export const createGame = async (game: Omit<Game, "id">): Promise<void> => {
try {
await axios.post(`${API_BASE_URL}/games`, game)
} catch (error) {
console.error("Error creating game:", error)
throw error
}
}