Certainly! Here's a comprehensive guide to help you design and implement the Medal Table web application as per your project specifications. This guide covers the essential steps, provides code snippets, and offers best practices to ensure a smooth development process.
1. Project Overview
You are to develop a web application that manages a medal table for medallists. The application comprises:
- Front-end: Developed using Vue.js to provide a dynamic and responsive user interface.
- Back-end: A REST-style Web API built with Node.js to handle CRUD operations.
- Database: SQLite for storing medallist information.
2. Technologies Stack
- Front-end: Vue.js, HTML, CSS
- Back-end: Node.js, Express.js
- Database: SQLite
- Tools: Git (for version control), Fetch API (for client-server communication)
3. Database Design
Your SQLite database (db.sqlite) should have a table named medallists with the following schema:
CREATE TABLE medallists (
pk INTEGER PRIMARY KEY AUTOINCREMENT,
nationality TEXT NOT NULL,
name TEXT NOT NULL,
goldMedal INTEGER DEFAULT 0,
silverMedal INTEGER DEFAULT 0,
bronzeMedal INTEGER DEFAULT 0
);
Sample Data Insertion:
INSERT INTO medallists (nationality, name, goldMedal, silverMedal, bronzeMedal)
VALUES
('USA', 'John Doe', 3, 2, 1),
('Canada', 'Jane Smith', 1, 3, 2);
4. Back-end: REST-style Web API with Node.js
4.1. Setting Up the Project
-
Initialize Node.js Project
mkdir medal-table-api
cd medal-table-api
npm init -y
-
Install Dependencies
npm install express sqlite3 cors body-parser
-
Project Structure
medal-table-api/
├── api.mjs
├── db.sqlite
└── package.json
4.2. Implementing api.mjs
Below is a sample implementation of the REST API using Express.js:
// api.mjs
import express from 'express';
import sqlite3 from 'sqlite3';
import { open } from 'sqlite';
import cors from 'cors';
import bodyParser from 'body-parser';
// Initialize Express app
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(bodyParser.json());
// Initialize and connect to SQLite database
let db;
(async () => {
db = await open({
filename: './db.sqlite',
driver: sqlite3.Database
});
// Create table if it doesn't exist
await db.run(`
CREATE TABLE IF NOT EXISTS medallists (
pk INTEGER PRIMARY KEY AUTOINCREMENT,
nationality TEXT NOT NULL,
name TEXT NOT NULL,
goldMedal INTEGER DEFAULT 0,
silverMedal INTEGER DEFAULT 0,
bronzeMedal INTEGER DEFAULT 0
)
`);
})();
// Helper function for error handling
const handleError = (res, error) => {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
};
// GET /medallists - Retrieve all medallists
app.get('/medallists', async (req, res) => {
try {
const medallists = await db.all('SELECT * FROM medallists');
res.status(200).json(medallists);
} catch (error) {
handleError(res, error);
}
});
// POST /medallists - Add a new medallist
app.post('/medallists', async (req, res) => {
const { nationality, name, goldMedal, silverMedal, bronzeMedal } = req.body;
// Input validation
if (!nationality || !name) {
return res.status(400).json({ error: 'Nationality and Name are required.' });
}
try {
const result = await db.run(
`INSERT INTO medallists (nationality, name, goldMedal, silverMedal, bronzeMedal)
VALUES (?, ?, ?, ?, ?)`,
[nationality, name, goldMedal || 0, silverMedal || 0, bronzeMedal || 0]
);
const newMedallist = await db.get('SELECT * FROM medallists WHERE pk = ?', [result.lastID]);
res.status(201).json(newMedallist);
} catch (error) {
handleError(res, error);
}
});
// PUT /medallists/:pk - Update a medallist
app.put('/medallists/:pk', async (req, res) => {
const { pk } = req.params;
const { nationality, name, goldMedal, silverMedal, bronzeMedal } = req.body;
// Input validation
if (!nationality || !name) {
return res.status(400).json({ error: 'Nationality and Name are required.' });
}
try {
const result = await db.run(
`UPDATE medallists
SET nationality = ?, name = ?, goldMedal = ?, silverMedal = ?, bronzeMedal = ?
WHERE pk = ?`,
[nationality, name, goldMedal || 0, silverMedal || 0, bronzeMedal || 0, pk]
);
if (result.changes === 0) {
return res.status(404).json({ error: 'Medallist not found.' });
}
const updatedMedallist = await db.get('SELECT * FROM medallists WHERE pk = ?', [pk]);
res.status(200).json(updatedMedallist);
} catch (error) {
handleError(res, error);
}
});
// DELETE /medallists/:pk - Delete a medallist
app.delete('/medallists/:pk', async (req, res) => {
const { pk } = req.params;
try {
const result = await db.run('DELETE FROM medallists WHERE pk = ?', [pk]);
if (result.changes === 0) {
return res.status(404).json({ error: 'Medallist not found.' });
}
res.status(200).json({ message: 'Medallist deleted successfully.' });
} catch (error) {
handleError(res, error);
}
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
4.3. Running the Server
Ensure your db.sqlite is in the same directory as api.mjs, then run:
node api.mjs
The server will be accessible at http://localhost:3000.
5. Front-end: Vue.js Application
5.1. Setting Up the Project
-
Install Vue CLI (if not already installed)
npm install -g @vue/cli
-
Create a New Vue Project
vue create medal-table-client
cd medal-table-client
Choose the default preset or customize as needed.
5.2. Project Structure
medal-table-client/
├── public/
├── src/
│ ├── components/
│ │ ├── MedalTable.vue
│ │ └── AddMedallist.vue
│ ├── App.vue
│ ├── main.js
├── package.json
└── ...
5.3. Implementing App.vue
Set up App.vue as the entry point and include necessary components.
<!-- App.vue -->
<template>
<div id="app">
<h1>Medal Table</h1>
<AddMedallist @add-success="fetchMedallists" />
<MedalTable
:medallists="medallists"
@delete-success="fetchMedallists"
@update-success="fetchMedallists"
/>
<div v-if="error" class="error">{{ error }}</div>
</div>
</template>
<script>
import MedalTable from './components/MedalTable.vue';
import AddMedallist from './components/AddMedallist.vue';
export default {
name: 'App',
components: {
MedalTable,
AddMedallist,
},
data() {
return {
medallists: [],
error: null,
};
},
methods: {
async fetchMedallists() {
try {
const response = await fetch('http://localhost:3000/medallists');
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
}
this.medallists = await response.json();
} catch (err) {
this.error = err.message;
}
},
},
created() {
this.fetchMedallists();
},
};
</script>
<style>
/* Add your styles here */
.error {
color: red;
margin-top: 20px;
}
</style>
5.4. Implementing AddMedallist.vue
Component to add a new medallist.
<!-- AddMedallist.vue -->
<template>
<div class="add-medallist">
<h2>Add New Medallist</h2>
<form @submit.prevent="addMedallist">
<div>
<label>Nationality:</label>
<input v-model="nationality" required />
</div>
<div>
<label>Name:</label>
<input v-model="name" required />
</div>
<div>
<label>Gold Medals:</label>
<input type="number" v-model.number="goldMedal" min="0" />
</div>
<div>
<label>Silver Medals:</label>
<input type="number" v-model.number="silverMedal" min="0" />
</div>
<div>
<label>Bronze Medals:</label>
<input type="number" v-model.number="bronzeMedal" min="0" />
</div>
<button type="submit">Add Medallist</button>
</form>
<div v-if="error" class="error">{{ error }}</div>
</div>
</template>
<script>
export default {
name: 'AddMedallist',
data() {
return {
nationality: '',
name: '',
goldMedal: 0,
silverMedal: 0,
bronzeMedal: 0,
error: null,
};
},
methods: {
async addMedallist() {
const newMedallist = {
nationality: this.nationality,
name: this.name,
goldMedal: this.goldMedal,
silverMedal: this.silverMedal,
bronzeMedal: this.bronzeMedal,
};
try {
const response = await fetch('http://localhost:3000/medallists', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newMedallist),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Failed to add medallist.');
}
// Clear form
this.nationality = '';
this.name = '';
this.goldMedal = 0;
this.silverMedal = 0;
this.bronzeMedal = 0;
this.error = null;
// Emit event to refresh medallists
this.$emit('add-success');
} catch (err) {
this.error = err.message;
}
},
},
};
</script>
<style>
/* Add your styles here */
.add-medallist {
margin-bottom: 30px;
}
.error {
color: red;
margin-top: 10px;
}
</style>
5.5. Implementing MedalTable.vue
Component to display, delete, sort, and calculate total medals.
<!-- MedalTable.vue -->
<template>
<div class="medal-table">
<h2>Medallists</h2>
<div class="controls">
<button @click="sortByGold">Sort by Gold Medals</button>
<button @click="sortByTotal">Sort by Total Medals</button>
<span>Total Medals: {{ totalMedals }}</span>
</div>
<table>
<thead>
<tr>
<th>Nationality</th>
<th>Name</th>
<th>Gold</th>
<th>Silver</th>
<th>Bronze</th>
<th>Total</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="medallist in sortedMedallists" :key="medallist.pk">
<td>{{ medallist.nationality }}</td>
<td>{{ medallist.name }}</td>
<td>{{ medallist.goldMedal }}</td>
<td>{{ medallist.silverMedal }}</td>
<td>{{ medallist.bronzeMedal }}</td>
<td>{{ medallist.goldMedal + medallist.silverMedal + medallist.bronzeMedal }}</td>
<td>
<button @click="deleteMedallist(medallist.pk)">Delete</button>
</td>
</tr>
</tbody>
</table>
<div v-if="error" class="error">{{ error }}</div>
</div>
</template>
<script>
export default {
name: 'MedalTable',
props: {
medallists: {
type: Array,
required: true,
},
},
data() {
return {
sortKey: '',
error: null,
};
},
computed: {
sortedMedallists() {
if (this.sortKey === 'gold') {
return [...this.medallists].sort((a, b) => b.goldMedal - a.goldMedal);
} else if (this.sortKey === 'total') {
return [...this.medallists].sort(
(a, b) =>
b.goldMedal + b.silverMedal + b.bronzeMedal -
(a.goldMedal + a.silverMedal + a.bronzeMedal)
);
}
return this.medallists;
},
totalMedals() {
return this.medallists.reduce(
(total, m) => total + m.goldMedal + m.silverMedal + m.bronzeMedal,
0
);
},
},
methods: {
sortByGold() {
this.sortKey = 'gold';
},
sortByTotal() {
this.sortKey = 'total';
},
async deleteMedallist(pk) {
if (!confirm('Are you sure you want to delete this medallist?')) return;
try {
const response = await fetch(`http://localhost:3000/medallists/${pk}`, {
method: 'DELETE',
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Failed to delete medallist.');
}
this.error = null;
this.$emit('delete-success');
} catch (err) {
this.error = err.message;
}
},
},
};
</script>
<style>
/* Add your styles here */
.medal-table table {
width: 100%;
border-collapse: collapse;
}
.medal-table th,
.medal-table td {
border: 1px solid #ddd;
padding: 8px;
}
.medal-table th {
background-color: #f2f2f2;
}
.controls {
margin-bottom: 15px;
}
.controls button {
margin-right: 10px;
}
.error {
color: red;
margin-top: 10px;
}
</style>
5.6. Running the Front-end
From the medal-table-client directory, run:
npm run serve
The application will be accessible at http://localhost:8080 (default Vue port).
6. Git Repository and Version Control
Using Git is crucial for collaboration and maintaining code integrity.
6.1. Initialize Git Repository
git init
6.2. Commit Changes
git add .
git commit -m "Initial commit: Set up front-end and back-end structure"
6.3. Branching Strategy
- Main Branch: Stable codebase.
- Feature Branches: Develop individual features.
Example Commands:
git checkout -b feature/add-medallist
# After implementing feature
git add .
git commit -m "Add functionality to add medallist"
git checkout main
git merge feature/add-medallist
git branch -d feature/add-medallist
6.4. Remote Repository
Assuming you’ve created a repository on GitHub:
git remote add origin https://github.com/yourusername/medal-table.git
git push -u origin main
Ensure to push both front-end and back-end code, possibly in separate folders or as a monorepo.
7. Additional Recommendations
- Error Handling: Enhance error messages for better user experience.
- Input Validation: Implement more robust validation on both client and server sides.
- UI/UX Enhancements: Use CSS frameworks like Bootstrap or Tailwind CSS for a more professional look.
- Authentication: If required, implement user authentication to secure the API.
- Testing: Write unit and integration tests to ensure reliability.
- Deployment: Consider deploying your application using platforms like Heroku, Vercel, or Netlify.
8. Conclusion
By following this guide, you should be well-equipped to develop the Medal Table web application. Ensure to regularly commit your changes, communicate with your team, and adhere to best coding practices. Good luck with your project!