feat: initial starter state for live-scoreboard
This commit is contained in:
commit
9c48064d5c
35
Jenkinsfile
vendored
Normal file
35
Jenkinsfile
vendored
Normal file
@ -0,0 +1,35 @@
|
||||
pipeline {
|
||||
agent any
|
||||
|
||||
stages {
|
||||
stage('Checkout') {
|
||||
steps {
|
||||
checkout scm
|
||||
}
|
||||
}
|
||||
|
||||
stage('API Unit & Contract Tests') {
|
||||
steps {
|
||||
sh 'node --test api/scoreboard.test.js'
|
||||
}
|
||||
}
|
||||
|
||||
stage('CLI Build & Tests') {
|
||||
steps {
|
||||
dir('cli') {
|
||||
sh '''
|
||||
npm ci --no-audit --no-fund || npm install --no-audit --no-fund
|
||||
npm run build
|
||||
npm test
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
always {
|
||||
deleteDir()
|
||||
}
|
||||
}
|
||||
}
|
||||
3
README.md
Normal file
3
README.md
Normal file
@ -0,0 +1,3 @@
|
||||
# live-scoreboard
|
||||
|
||||
Node.js 20 LTS Express API (`api/`), zero-bundler Vanilla browser SPA (`frontend/`), TypeScript `fx-rate` CLI (`cli/`), and Playwright headless UI E2E suite (`tests/`) used in **Ex 3.3**, **Ex 5.2**, **Ex 5.3**, and **Ex 6.4**.
|
||||
117
api/scoreboard.js
Normal file
117
api/scoreboard.js
Normal file
@ -0,0 +1,117 @@
|
||||
/**
|
||||
* Pure Node.js 20 in-memory scoreboard store and HTTP request handler.
|
||||
* Zero external runtime dependencies so unit tests execute fast via `node --test`.
|
||||
*/
|
||||
|
||||
export class ScoreboardStore {
|
||||
constructor() {
|
||||
this.scores = new Map();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds (or subtracts) integer points for a named team.
|
||||
* @param {string} rawTeam
|
||||
* @param {number} points
|
||||
* @returns {Array<{team: string, points: number}>}
|
||||
*/
|
||||
recordScore(rawTeam, points) {
|
||||
if (typeof rawTeam !== 'string' || rawTeam.trim().length === 0) {
|
||||
throw new Error('team must be a non-empty string');
|
||||
}
|
||||
if (typeof points !== 'number' || !Number.isFinite(points) || !Number.isInteger(points)) {
|
||||
throw new Error('points must be a finite integer');
|
||||
}
|
||||
|
||||
const team = rawTeam.trim();
|
||||
const current = this.scores.get(team) ?? 0;
|
||||
this.scores.set(team, current + points);
|
||||
return this.getLeaderboard();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns teams sorted descending by score, then ascending alphabetically.
|
||||
* @returns {Array<{team: string, points: number}>}
|
||||
*/
|
||||
getLeaderboard() {
|
||||
return Array.from(this.scores.entries())
|
||||
.map(([team, points]) => ({ team, points }))
|
||||
.sort((a, b) => (b.points - a.points) || a.team.localeCompare(b.team));
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.scores.clear();
|
||||
}
|
||||
}
|
||||
|
||||
function sendJson(res, statusCode, payload) {
|
||||
res.statusCode = statusCode;
|
||||
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||||
res.end(JSON.stringify(payload));
|
||||
}
|
||||
|
||||
function readJsonBody(req) {
|
||||
if (req.body && typeof req.body === 'object') {
|
||||
return Promise.resolve(req.body);
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks = [];
|
||||
req.on('data', (chunk) => chunks.push(chunk));
|
||||
req.on('end', () => {
|
||||
if (chunks.length === 0) {
|
||||
resolve({});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
||||
} catch {
|
||||
reject(new Error('Invalid JSON payload'));
|
||||
}
|
||||
});
|
||||
req.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a standard Node HTTP / Express middleware handler for `/api/*` routes.
|
||||
* @param {ScoreboardStore} store
|
||||
*/
|
||||
export function createApiHandler(store) {
|
||||
return async (req, res) => {
|
||||
const rawPath = (req.url || '/').split('?')[0];
|
||||
const path = rawPath.startsWith('/api/')
|
||||
? rawPath.slice(4)
|
||||
: rawPath === '/api'
|
||||
? '/'
|
||||
: rawPath;
|
||||
const method = (req.method || 'GET').toUpperCase();
|
||||
|
||||
if (method === 'GET' && path === '/health') {
|
||||
sendJson(res, 200, { status: 'ok' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === 'GET' && path === '/scores') {
|
||||
sendJson(res, 200, { teams: store.getLeaderboard() });
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === 'POST' && path === '/scores/reset') {
|
||||
store.reset();
|
||||
sendJson(res, 200, { teams: [] });
|
||||
return;
|
||||
}
|
||||
|
||||
if (method === 'POST' && path === '/scores') {
|
||||
try {
|
||||
const body = await readJsonBody(req);
|
||||
const teams = store.recordScore(body.team, body.points);
|
||||
sendJson(res, 201, { teams });
|
||||
} catch (err) {
|
||||
sendJson(res, 400, { error: err.message });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
sendJson(res, 404, { error: `Route not found: ${method} ${path}` });
|
||||
};
|
||||
}
|
||||
73
api/scoreboard.test.js
Normal file
73
api/scoreboard.test.js
Normal file
@ -0,0 +1,73 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import http from 'node:http';
|
||||
import { ScoreboardStore, createApiHandler } from './scoreboard.js';
|
||||
|
||||
async function withServer(fn) {
|
||||
const store = new ScoreboardStore();
|
||||
const server = http.createServer(createApiHandler(store));
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const { port } = server.address();
|
||||
const baseUrl = `http://127.0.0.1:${port}`;
|
||||
try {
|
||||
await fn(baseUrl, store);
|
||||
} finally {
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
}
|
||||
}
|
||||
|
||||
describe('ScoreboardStore', () => {
|
||||
it('accumulates scores and orders descending with alphabetical tie-breaks', () => {
|
||||
const store = new ScoreboardStore();
|
||||
store.recordScore('Zebra', 10);
|
||||
store.recordScore('Alpha', 10);
|
||||
store.recordScore('Beta', 25);
|
||||
store.recordScore('Alpha', 15);
|
||||
|
||||
assert.deepEqual(store.getLeaderboard(), [
|
||||
{ team: 'Alpha', points: 25 },
|
||||
{ team: 'Beta', points: 25 },
|
||||
{ team: 'Zebra', points: 10 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('rejects blank team names and non-integer scores', () => {
|
||||
const store = new ScoreboardStore();
|
||||
assert.throws(() => store.recordScore(' ', 10), /non-empty/);
|
||||
assert.throws(() => store.recordScore('Alpha', 1.5), /finite integer/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Scoreboard HTTP API', () => {
|
||||
it('supports health check, score recording, retrieval, reset, and 400 errors', async () => {
|
||||
await withServer(async (baseUrl) => {
|
||||
const healthRes = await fetch(`${baseUrl}/api/health`);
|
||||
assert.equal(healthRes.status, 200);
|
||||
assert.deepEqual(await healthRes.json(), { status: 'ok' });
|
||||
|
||||
const createRes = await fetch(`${baseUrl}/api/scores`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ team: 'Team Nova', points: 40 }),
|
||||
});
|
||||
assert.equal(createRes.status, 201);
|
||||
const created = await createRes.json();
|
||||
assert.deepEqual(created.teams, [{ team: 'Team Nova', points: 40 }]);
|
||||
|
||||
const invalidRes = await fetch(`${baseUrl}/api/scores`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ team: '', points: 10 }),
|
||||
});
|
||||
assert.equal(invalidRes.status, 400);
|
||||
|
||||
const listRes = await fetch(`${baseUrl}/api/scores`);
|
||||
assert.equal(listRes.status, 200);
|
||||
assert.equal((await listRes.json()).teams.length, 1);
|
||||
|
||||
const resetRes = await fetch(`${baseUrl}/api/scores/reset`, { method: 'POST' });
|
||||
assert.equal(resetRes.status, 200);
|
||||
assert.deepEqual(await resetRes.json(), { teams: [] });
|
||||
});
|
||||
});
|
||||
});
|
||||
23
api/server.js
Normal file
23
api/server.js
Normal file
@ -0,0 +1,23 @@
|
||||
import express from 'express';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { ScoreboardStore, createApiHandler } from './scoreboard.js';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const frontendDir = path.resolve(__dirname, '..', 'frontend');
|
||||
|
||||
const app = express();
|
||||
const store = new ScoreboardStore();
|
||||
|
||||
app.use('/api', createApiHandler(store));
|
||||
app.use(express.static(frontendDir));
|
||||
|
||||
app.get('*', (_req, res) => {
|
||||
res.sendFile(path.join(frontendDir, 'index.html'));
|
||||
});
|
||||
|
||||
const port = Number(process.env.PORT || 3000);
|
||||
app.listen(port, '0.0.0.0', () => {
|
||||
console.log(`live-scoreboard listening on http://0.0.0.0:${port}`);
|
||||
});
|
||||
5
cli/jest.config.cjs
Normal file
5
cli/jest.config.cjs
Normal file
@ -0,0 +1,5 @@
|
||||
module.exports = {
|
||||
preset: 'ts-jest',
|
||||
testEnvironment: 'node',
|
||||
roots: ['<rootDir>/tests'],
|
||||
};
|
||||
18
cli/package.json
Normal file
18
cli/package.json
Normal file
@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "fx-rate-cli",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "TypeScript currency conversion CLI for CND-400 Node/TS CI pipeline labs.",
|
||||
"main": "dist/fx-rate.js",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"test": "jest"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/node": "^20.17.6",
|
||||
"jest": "^29.7.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"typescript": "^5.6.3"
|
||||
}
|
||||
}
|
||||
44
cli/src/fx-rate.ts
Normal file
44
cli/src/fx-rate.ts
Normal file
@ -0,0 +1,44 @@
|
||||
import { USD_RATES } from './rate-table';
|
||||
|
||||
/**
|
||||
* Converts a monetary amount between two supported ISO currency codes.
|
||||
*/
|
||||
export function convertCurrency(amount: number, fromCurrency: string, toCurrency: string): number {
|
||||
if (!Number.isFinite(amount) || amount < 0) {
|
||||
throw new Error(`Amount must be a finite non-negative number: ${amount}`);
|
||||
}
|
||||
const src = fromCurrency.trim().toUpperCase();
|
||||
const dst = toCurrency.trim().toUpperCase();
|
||||
|
||||
const srcRate = USD_RATES[src];
|
||||
const dstRate = USD_RATES[dst];
|
||||
if (srcRate === undefined) {
|
||||
throw new Error(`Unsupported source currency: ${fromCurrency}`);
|
||||
}
|
||||
if (dstRate === undefined) {
|
||||
throw new Error(`Unsupported target currency: ${toCurrency}`);
|
||||
}
|
||||
|
||||
const usdAmount = amount / srcRate;
|
||||
return Number((usdAmount * dstRate).toFixed(4));
|
||||
}
|
||||
|
||||
export function runCli(argv: string[]): number {
|
||||
if (argv.length < 3) {
|
||||
console.error('Usage: fx-rate <amount> <from> <to>');
|
||||
return 1;
|
||||
}
|
||||
const amount = Number(argv[0]);
|
||||
try {
|
||||
const converted = convertCurrency(amount, argv[1], argv[2]);
|
||||
console.log(`${amount} ${argv[1].toUpperCase()} = ${converted} ${argv[2].toUpperCase()}`);
|
||||
return 0;
|
||||
} catch (err) {
|
||||
console.error(`Error: ${(err as Error).message}`);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
process.exitCode = runCli(process.argv.slice(2));
|
||||
}
|
||||
8
cli/src/rate-table.ts
Normal file
8
cli/src/rate-table.ts
Normal file
@ -0,0 +1,8 @@
|
||||
/** Reference USD-base exchange rates used by the fx-rate CLI. */
|
||||
export const USD_RATES: Record<string, number> = {
|
||||
USD: 1.0,
|
||||
EUR: 0.92,
|
||||
GBP: 0.79,
|
||||
SGD: 1.34,
|
||||
JPY: 152.5,
|
||||
};
|
||||
24
cli/tests/fx-rate.test.ts
Normal file
24
cli/tests/fx-rate.test.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import { convertCurrency, runCli } from '../src/fx-rate';
|
||||
|
||||
describe('fx-rate converter', () => {
|
||||
test('converts USD to EUR accurately', () => {
|
||||
expect(convertCurrency(100, 'USD', 'EUR')).toBe(92);
|
||||
});
|
||||
|
||||
test('normalizes lowercase currency codes and cross-converts via USD', () => {
|
||||
const gbp = convertCurrency(134, 'sgd', 'gbp');
|
||||
expect(gbp).toBe(79);
|
||||
});
|
||||
|
||||
test('throws on negative amounts or unknown currencies', () => {
|
||||
expect(() => convertCurrency(-5, 'USD', 'EUR')).toThrow(/non-negative/);
|
||||
expect(() => convertCurrency(10, 'XYZ', 'USD')).toThrow(/Unsupported source/);
|
||||
expect(() => convertCurrency(10, 'USD', 'ABC')).toThrow(/Unsupported target/);
|
||||
});
|
||||
|
||||
test('CLI returns non-zero exit code for insufficient args', () => {
|
||||
const errSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
|
||||
expect(runCli(['100', 'USD'])).toBe(1);
|
||||
errSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
15
cli/tsconfig.json
Normal file
15
cli/tsconfig.json
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "CommonJS",
|
||||
"moduleResolution": "Node",
|
||||
"rootDir": "src",
|
||||
"outDir": "dist",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["node_modules", "dist", "tests"]
|
||||
}
|
||||
63
frontend/app.js
Normal file
63
frontend/app.js
Normal file
@ -0,0 +1,63 @@
|
||||
const form = document.getElementById('score-form');
|
||||
const teamInput = document.getElementById('team-name');
|
||||
const pointsInput = document.getElementById('points-input');
|
||||
const resetButton = document.getElementById('reset-board');
|
||||
const errorBanner = document.getElementById('error-banner');
|
||||
const leaderboardBody = document.getElementById('leaderboard-body');
|
||||
|
||||
function renderLeaderboard(teams) {
|
||||
leaderboardBody.replaceChildren();
|
||||
for (const [idx, entry] of teams.entries()) {
|
||||
const tr = document.createElement('tr');
|
||||
tr.dataset.testid = 'leaderboard-row';
|
||||
|
||||
const rankTd = document.createElement('td');
|
||||
rankTd.textContent = String(idx + 1);
|
||||
|
||||
const teamTd = document.createElement('td');
|
||||
teamTd.textContent = entry.team;
|
||||
|
||||
const pointsTd = document.createElement('td');
|
||||
pointsTd.textContent = String(entry.points);
|
||||
|
||||
tr.append(rankTd, teamTd, pointsTd);
|
||||
leaderboardBody.appendChild(tr);
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchLeaderboard() {
|
||||
const res = await fetch('/api/scores');
|
||||
const data = await res.json();
|
||||
renderLeaderboard(data.teams || []);
|
||||
}
|
||||
|
||||
form.addEventListener('submit', async (event) => {
|
||||
event.preventDefault();
|
||||
errorBanner.textContent = '';
|
||||
|
||||
const team = teamInput.value.trim();
|
||||
const points = Number.parseInt(pointsInput.value, 10);
|
||||
|
||||
const res = await fetch('/api/scores', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ team, points }),
|
||||
});
|
||||
|
||||
const payload = await res.json();
|
||||
if (!res.ok) {
|
||||
errorBanner.textContent = payload.error || 'Failed to record score';
|
||||
return;
|
||||
}
|
||||
renderLeaderboard(payload.teams || []);
|
||||
form.reset();
|
||||
});
|
||||
|
||||
resetButton.addEventListener('click', async () => {
|
||||
errorBanner.textContent = '';
|
||||
const res = await fetch('/api/scores/reset', { method: 'POST' });
|
||||
const payload = await res.json();
|
||||
renderLeaderboard(payload.teams || []);
|
||||
});
|
||||
|
||||
fetchLeaderboard();
|
||||
42
frontend/index.html
Normal file
42
frontend/index.html
Normal file
@ -0,0 +1,42 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>CloudOps Live Scoreboard</title>
|
||||
<style>
|
||||
:root { font-family: system-ui, -apple-system, sans-serif; color: #0f172a; background: #f8fafc; }
|
||||
main { max-width: 680px; margin: 2.5rem auto; padding: 1.5rem; background: #ffffff; border-radius: 10px; box-shadow: 0 2px 10px rgba(15, 23, 42, 0.08); }
|
||||
form { display: flex; gap: 0.5rem; flex-wrap: wrap; margin-bottom: 1.25rem; }
|
||||
input, button { padding: 0.55rem 0.75rem; font-size: 0.95rem; border-radius: 6px; border: 1px solid #cbd5e1; }
|
||||
button { background: #2563eb; color: #ffffff; border-color: #2563eb; cursor: pointer; font-weight: 600; }
|
||||
button.secondary { background: #e2e8f0; color: #1e293b; border-color: #cbd5e1; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th, td { text-align: left; padding: 0.6rem; border-bottom: 1px solid #e2e8f0; }
|
||||
#error-banner { color: #b91c1c; min-height: 1.25rem; margin-bottom: 0.75rem; font-size: 0.9rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Live Scoreboard</h1>
|
||||
<form id="score-form">
|
||||
<input id="team-name" data-testid="team-input" type="text" placeholder="Team name" required />
|
||||
<input id="points-input" data-testid="points-input" type="number" step="1" placeholder="Points" required />
|
||||
<button id="submit-score" data-testid="submit-score" type="submit">Record Score</button>
|
||||
<button id="reset-board" data-testid="reset-board" type="button" class="secondary">Reset</button>
|
||||
</form>
|
||||
<div id="error-banner" role="alert"></div>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>Team</th>
|
||||
<th>Points</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="leaderboard-body"></tbody>
|
||||
</table>
|
||||
</main>
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
18
package.json
Normal file
18
package.json
Normal file
@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "live-scoreboard",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "CND-400 Node.js 20 scoreboard API, vanilla SPA, TypeScript CLI, and Playwright E2E suite.",
|
||||
"scripts": {
|
||||
"start": "node api/server.js",
|
||||
"test": "node --test api/scoreboard.test.js",
|
||||
"test:e2e": "playwright test"
|
||||
},
|
||||
"dependencies": {
|
||||
"express": "^4.21.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "1.49.0"
|
||||
}
|
||||
}
|
||||
18
playwright.config.ts
Normal file
18
playwright.config.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { defineConfig } from '@playwright/test';
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './tests',
|
||||
timeout: 30_000,
|
||||
fullyParallel: false,
|
||||
use: {
|
||||
baseURL: 'http://127.0.0.1:3000',
|
||||
headless: true,
|
||||
trace: 'retain-on-failure',
|
||||
},
|
||||
webServer: {
|
||||
command: 'node api/server.js',
|
||||
url: 'http://127.0.0.1:3000/api/health',
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 20_000,
|
||||
},
|
||||
});
|
||||
20
tests/score-flow.spec.ts
Normal file
20
tests/score-flow.spec.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
test('submitting team scores updates sorted leaderboard', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await page.getByTestId('reset-board').click();
|
||||
|
||||
await page.getByTestId('team-input').fill('Team Alpha');
|
||||
await page.getByTestId('points-input').fill('10');
|
||||
await page.getByTestId('submit-score').click();
|
||||
|
||||
await page.getByTestId('team-input').fill('Team Beta');
|
||||
await page.getByTestId('points-input').fill('25');
|
||||
await page.getByTestId('submit-score').click();
|
||||
|
||||
const rows = page.getByTestId('leaderboard-row');
|
||||
await expect(rows).toHaveCount(2);
|
||||
await expect(rows.nth(0)).toContainText('Team Beta');
|
||||
await expect(rows.nth(0)).toContainText('25');
|
||||
await expect(rows.nth(1)).toContainText('Team Alpha');
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user