Skip to content

Commit 625f568

Browse files
committed
add cypress and workflows
1 parent 1850040 commit 625f568

14 files changed

Lines changed: 2605 additions & 1667 deletions

File tree

.github/workflows/test.yaml

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# yaml-language-server: $schema=https://raw.githubusercontent.com/SchemaStore/schemastore/refs/heads/master/src/schemas/json/github-workflow.json
2+
name: Test with Postgres 16
3+
4+
on:
5+
workflow_dispatch:
6+
pull_request:
7+
types: [opened, synchronize]
8+
push:
9+
10+
jobs:
11+
test-run:
12+
runs-on: ubuntu-24.04
13+
steps:
14+
- uses: actions/checkout@v4
15+
- name: Run Postgres
16+
run: |
17+
sudo tee -a /etc/postgresql/16/main/postgresql.conf <<EOF
18+
shared_preload_libraries = 'auto_explain'
19+
auto_explain.log_min_duration = 0
20+
auto_explain.log_analyze = true
21+
auto_explain.log_verbose = true
22+
auto_explain.log_buffers = true
23+
auto_explain.log_format = 'json'
24+
logging_collector = on
25+
log_directory = '/var/log/postgresql'
26+
log_filename = 'postgres.log'
27+
EOF
28+
sudo tee /etc/postgresql/16/main/pg_hba.conf > /dev/null <<EOF
29+
host all all 127.0.0.1/32 trust
30+
host all all ::1/128 trust
31+
local all all peer
32+
EOF
33+
sudo systemctl start postgresql.service
34+
sudo -u postgres createuser -s -d -r -w query_doctor
35+
sudo -u postgres createdb leaderboard
36+
sudo chmod 666 /var/log/postgresql/postgres.log
37+
38+
- name: Run migrations
39+
run: |
40+
psql -h localhost -U query_doctor -d leaderboard -f db/init.sql
41+
42+
- name: Compile TypeScript
43+
run: |
44+
npm run build
45+
46+
- name: Run backend
47+
run: node ./dist/app.js &
48+
env:
49+
PORT: 3123
50+
DATABASE_URL: postgres://query_doctor@localhost:5432/leaderboard
51+
52+
- name: Cypress run
53+
uses: cypress-io/github-action@v6
54+
55+
- name: Run local GitHub Action
56+
uses: query-doctor/analyzer@v0
57+
env:
58+
GITHUB_TOKEN: ${{ github.token }}
59+
POSTGRES_URL: http://query_doctor@localhost:5432/leaderboard
60+
LOG_PATH: /var/log/postgresql/postgres.log

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
node_modules
22
.env
3+
dist

cypress.config.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { defineConfig } from "cypress";
2+
3+
export default defineConfig({
4+
e2e: {
5+
setupNodeEvents(on, config) {
6+
// implement node event listeners here
7+
},
8+
},
9+
});

cypress/e2e/spec.cy.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
describe("template spec", () => {
2+
it("passes", () => {
3+
cy.visit("http://localhost:3123");
4+
cy.get(".player-link").first().click();
5+
// goback one page
6+
cy.go("back");
7+
cy.get("[name=name]").type("John Doe");
8+
cy.get(".play-game").click();
9+
cy.get(".submit-score").click();
10+
});
11+
});

cypress/fixtures/example.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"name": "Using fixtures to represent data",
3+
"email": "hello@cypress.io",
4+
"body": "Fixtures are a great way to mock data for responses to routes"
5+
}

cypress/support/commands.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/// <reference types="cypress" />
2+
// ***********************************************
3+
// This example commands.ts shows you how to
4+
// create various custom commands and overwrite
5+
// existing commands.
6+
//
7+
// For more comprehensive examples of custom
8+
// commands please read more here:
9+
// https://on.cypress.io/custom-commands
10+
// ***********************************************
11+
//
12+
//
13+
// -- This is a parent command --
14+
// Cypress.Commands.add('login', (email, password) => { ... })
15+
//
16+
//
17+
// -- This is a child command --
18+
// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
19+
//
20+
//
21+
// -- This is a dual command --
22+
// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
23+
//
24+
//
25+
// -- This will overwrite an existing command --
26+
// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })
27+
//
28+
// declare global {
29+
// namespace Cypress {
30+
// interface Chainable {
31+
// login(email: string, password: string): Chainable<void>
32+
// drag(subject: string, options?: Partial<TypeOptions>): Chainable<Element>
33+
// dismiss(subject: string, options?: Partial<TypeOptions>): Chainable<Element>
34+
// visit(originalFn: CommandOriginalFn, url: string, options: Partial<VisitOptions>): Chainable<Element>
35+
// }
36+
// }
37+
// }

cypress/support/e2e.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// ***********************************************************
2+
// This example support/e2e.ts is processed and
3+
// loaded automatically before your test files.
4+
//
5+
// This is a great place to put global configuration and
6+
// behavior that modifies Cypress.
7+
//
8+
// You can change the location of this file or turn off
9+
// automatically serving support files with the
10+
// 'supportFile' configuration option.
11+
//
12+
// You can read more here:
13+
// https://on.cypress.io/configuration
14+
// ***********************************************************
15+
16+
// Import commands.js using ES2015 syntax:
17+
import './commands'

dist/app.js

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
"use strict";
2+
var __importDefault = (this && this.__importDefault) || function (mod) {
3+
return (mod && mod.__esModule) ? mod : { "default": mod };
4+
};
5+
Object.defineProperty(exports, "__esModule", { value: true });
6+
const express_1 = __importDefault(require("express"));
7+
const pg_1 = require("pg");
8+
const dotenv_1 = __importDefault(require("dotenv"));
9+
const path_1 = __importDefault(require("path"));
10+
dotenv_1.default.config();
11+
const app = (0, express_1.default)();
12+
const pool = new pg_1.Pool({ connectionString: process.env.DATABASE_URL });
13+
app.set("view engine", "ejs");
14+
app.set("views", path_1.default.join(__dirname, "../views"));
15+
app.use(express_1.default.static(path_1.default.join(__dirname, "../public")));
16+
app.use(express_1.default.json());
17+
app.get("/", async (_req, res) => {
18+
const result = await pool.query(`
19+
SELECT u.name, s.score, to_char(s.timestamp, 'HH24:MI:SS') AS time
20+
FROM scores s
21+
JOIN users u ON u.id = s.user_id
22+
ORDER BY s.score DESC
23+
LIMIT 10
24+
`);
25+
res.render("index", { scores: result.rows });
26+
});
27+
app.get("/player/:name", async (req, res) => {
28+
const name = req.params.name;
29+
const stats = await pool.query(`
30+
SELECT
31+
COUNT(*) AS games_played,
32+
MAX(score) AS high_score,
33+
ROUND(AVG(score))::int AS avg_score,
34+
MAX(timestamp) AS last_played
35+
FROM scores s
36+
JOIN users u ON u.id = s.user_id
37+
WHERE u.name = $1
38+
`, [name]);
39+
const recent = await pool.query(`
40+
SELECT score, to_char(s.timestamp, 'YYYY-MM-DD HH24:MI') as time
41+
FROM scores s
42+
JOIN users u ON u.id = s.user_id
43+
WHERE u.name = $1
44+
ORDER BY s.timestamp DESC
45+
LIMIT 10
46+
`, [name]);
47+
const leaderboardContext = await pool.query(`
48+
WITH ranked AS (
49+
SELECT
50+
u.name,
51+
s.score,
52+
RANK() OVER (ORDER BY s.score DESC) AS rank
53+
FROM scores s
54+
JOIN users u ON u.id = s.user_id
55+
),
56+
target AS (
57+
SELECT rank FROM ranked WHERE name = $1 ORDER BY score DESC LIMIT 1
58+
)
59+
SELECT * FROM ranked
60+
WHERE rank BETWEEN (SELECT rank FROM target) - 2 AND (SELECT rank FROM target) + 2
61+
ORDER BY rank;
62+
`, [name]);
63+
res.render("player", {
64+
name,
65+
stats: stats.rows[0],
66+
recent: recent.rows,
67+
leaderboardContext: leaderboardContext.rows,
68+
});
69+
});
70+
app.post("/submit", async (req, res) => {
71+
const { name, score } = req.body;
72+
const parsedScore = parseInt(score, 10);
73+
if (!name || isNaN(parsedScore))
74+
return res.status(400).send("Invalid input");
75+
const userId = await findOrCreateUser(name);
76+
await pool.query(`INSERT INTO scores (user_id, score) VALUES ($1, $2)`, [
77+
userId,
78+
parsedScore,
79+
]);
80+
res.redirect(`/player/${encodeURIComponent(name)}`);
81+
});
82+
// Helpers
83+
async function findOrCreateUser(name) {
84+
const existing = await pool.query(`SELECT id FROM users WHERE name = $1`, [
85+
name,
86+
]);
87+
if (existing.rows.length > 0)
88+
return existing.rows[0].id;
89+
const created = await pool.query(`INSERT INTO users (name) VALUES ($1) RETURNING id`, [name]);
90+
return created.rows[0].id;
91+
}
92+
const PORT = process.env.PORT || 3123;
93+
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));

0 commit comments

Comments
 (0)