From f6fb3e02185878aa55dc8e83b2c0551ea3d3889c Mon Sep 17 00:00:00 2001 From: CloudOps Lab Bot Date: Tue, 24 Nov 2026 11:14:02 +0800 Subject: [PATCH] feat: initial starter state for live-scoreboard --- Jenkinsfile | 35 ++++++++++++ README.md | 3 + api/scoreboard.js | 117 ++++++++++++++++++++++++++++++++++++++ api/scoreboard.test.js | 73 ++++++++++++++++++++++++ api/server.js | 23 ++++++++ cli/jest.config.cjs | 5 ++ cli/package.json | 18 ++++++ cli/src/fx-rate.ts | 44 ++++++++++++++ cli/src/rate-table.ts | 8 +++ cli/tests/fx-rate.test.ts | 24 ++++++++ cli/tsconfig.json | 15 +++++ frontend/app.js | 63 ++++++++++++++++++++ frontend/index.html | 42 ++++++++++++++ package.json | 18 ++++++ playwright.config.ts | 18 ++++++ tests/score-flow.spec.ts | 20 +++++++ 16 files changed, 526 insertions(+) create mode 100644 Jenkinsfile create mode 100644 README.md create mode 100644 api/scoreboard.js create mode 100644 api/scoreboard.test.js create mode 100644 api/server.js create mode 100644 cli/jest.config.cjs create mode 100644 cli/package.json create mode 100644 cli/src/fx-rate.ts create mode 100644 cli/src/rate-table.ts create mode 100644 cli/tests/fx-rate.test.ts create mode 100644 cli/tsconfig.json create mode 100644 frontend/app.js create mode 100644 frontend/index.html create mode 100644 package.json create mode 100644 playwright.config.ts create mode 100644 tests/score-flow.spec.ts diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..a09916a --- /dev/null +++ b/Jenkinsfile @@ -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() + } + } +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..f3013d5 --- /dev/null +++ b/README.md @@ -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**. diff --git a/api/scoreboard.js b/api/scoreboard.js new file mode 100644 index 0000000..a31c3f2 --- /dev/null +++ b/api/scoreboard.js @@ -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}` }); + }; +} diff --git a/api/scoreboard.test.js b/api/scoreboard.test.js new file mode 100644 index 0000000..387c364 --- /dev/null +++ b/api/scoreboard.test.js @@ -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: [] }); + }); + }); +}); diff --git a/api/server.js b/api/server.js new file mode 100644 index 0000000..e91e26f --- /dev/null +++ b/api/server.js @@ -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}`); +}); diff --git a/cli/jest.config.cjs b/cli/jest.config.cjs new file mode 100644 index 0000000..a3794ac --- /dev/null +++ b/cli/jest.config.cjs @@ -0,0 +1,5 @@ +module.exports = { + preset: 'ts-jest', + testEnvironment: 'node', + roots: ['/tests'], +}; diff --git a/cli/package.json b/cli/package.json new file mode 100644 index 0000000..833c9a6 --- /dev/null +++ b/cli/package.json @@ -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" + } +} diff --git a/cli/src/fx-rate.ts b/cli/src/fx-rate.ts new file mode 100644 index 0000000..2f75e19 --- /dev/null +++ b/cli/src/fx-rate.ts @@ -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 '); + 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)); +} diff --git a/cli/src/rate-table.ts b/cli/src/rate-table.ts new file mode 100644 index 0000000..389c48c --- /dev/null +++ b/cli/src/rate-table.ts @@ -0,0 +1,8 @@ +/** Reference USD-base exchange rates used by the fx-rate CLI. */ +export const USD_RATES: Record = { + USD: 1.0, + EUR: 0.92, + GBP: 0.79, + SGD: 1.34, + JPY: 152.5, +}; diff --git a/cli/tests/fx-rate.test.ts b/cli/tests/fx-rate.test.ts new file mode 100644 index 0000000..9c57dca --- /dev/null +++ b/cli/tests/fx-rate.test.ts @@ -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(); + }); +}); diff --git a/cli/tsconfig.json b/cli/tsconfig.json new file mode 100644 index 0000000..50b6589 --- /dev/null +++ b/cli/tsconfig.json @@ -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"] +} diff --git a/frontend/app.js b/frontend/app.js new file mode 100644 index 0000000..690da38 --- /dev/null +++ b/frontend/app.js @@ -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(); diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..06de72e --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,42 @@ + + + + + + CloudOps Live Scoreboard + + + +
+

Live Scoreboard

+
+ + + + +
+ + + + + + + + + + +
#TeamPoints
+
+ + + diff --git a/package.json b/package.json new file mode 100644 index 0000000..523a1b4 --- /dev/null +++ b/package.json @@ -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" + } +} diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 0000000..c88ad12 --- /dev/null +++ b/playwright.config.ts @@ -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, + }, +}); diff --git a/tests/score-flow.spec.ts b/tests/score-flow.spec.ts new file mode 100644 index 0000000..0cfeb79 --- /dev/null +++ b/tests/score-flow.spec.ts @@ -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'); +});