Complete Full-Stack Todo application with Angular, Node.js, and MySQL

This commit is contained in:
2026-01-12 13:25:31 +05:30
parent ec811d9f97
commit f56a6bbaa4
39 changed files with 15083 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
[*.md]
max_line_length = off
trim_trailing_whitespace = false

42
To do list har/todo-list/.gitignore vendored Normal file
View File

@@ -0,0 +1,42 @@
# See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
node_modules/
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db

View File

@@ -0,0 +1,4 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
"recommendations": ["angular.ng-template"]
}

View File

@@ -0,0 +1,20 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "ng serve",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: start",
"url": "http://localhost:4200/"
},
{
"name": "ng test",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: test",
"url": "http://localhost:9876/debug.html"
}
]
}

View File

@@ -0,0 +1,42 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "start",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
},
{
"type": "npm",
"script": "test",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
}
]
}

View File

@@ -0,0 +1,46 @@
# Full-Stack Todo Application
This is a complete Todo management system that transitions from a simple frontend to a full-stack architecture using the **PEAN stack** (PostgreSQL/MySQL, Express, Angular, Node).
## Features
- **Frontend**: Responsive UI built with Angular 17.
- **Backend**: RESTful API powered by Node.js and Express.
- **Database**: Persistent storage using MySQL 5.5.
- **Full CRUD**: Support for Adding, Viewing, Toggling, and Deleting tasks.
- **Security**: Configured with CORS and Helmet middleware.
## Project Structure
- `/src`: Angular frontend source code.
- `/backend`: Node.js server and API logic.
## Setup Instructions
### 1. Database Configuration
Ensure MySQL is running and execute the following SQL:
```sql
CREATE DATABASE todo_db;
USE todo_db;
CREATE TABLE todos (
sno BIGINT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
`desc` TEXT,
active BOOLEAN DEFAULT TRUE
);
### 2. Run the Backend
- Navigate to the backend folder: cd backend
- Install dependencies: npm install
- Start the server: node index.js The server will run on http://localhost:3000
### 3. Run the Frontend
- Return to the root folder: cd ..
- Install dependencies: npm install
- Start the app: ng serve The app will be available at http://localhost:4200
## Key Implementation Details
- HttpClient: Used for communication between Angular and the Node.js API.
- MySQL Pool: Implemented connection pooling for efficient database queries.
- Data Persistence: Data is saved to MySQL, ensuring it survives browser refreshes and server restarts.
Developed by Harshit Anand Sachdev

View File

@@ -0,0 +1,99 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"todo-list": {
"projectType": "application",
"schematics": {},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/todo-list",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": [
"zone.js"
],
"tsConfig": "tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css",
"./node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"
]
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"buildTarget": "todo-list:build:production"
},
"development": {
"buildTarget": "todo-list:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"buildTarget": "todo-list:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": [
"zone.js",
"zone.js/testing"
],
"tsConfig": "tsconfig.spec.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": []
}
}
}
}
}
}

View File

@@ -0,0 +1,88 @@
const express = require('express');
const mysql = require('mysql2');
const cors = require('cors');
const helmet = require('helmet');
const app = express();
// 1. Security Headers (Fixes the CSP error)
app.use(helmet({
contentSecurityPolicy: false, // Easiest for local development
}));
// 2. Allow Angular to connect
app.use(cors());
app.use(express.json());
// 3. MySQL Connection Pool
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '123456', // Ensure this matches your MySQL password
database: 'todo_db'
}).promise();
// 4. Root Route (Fixes the GET / 404)
app.get('/', (req, res) => {
res.send("Todo Backend is Online");
});
// 5. Silences the Chrome DevTools error
app.get('/favicon.ico', (req, res) => res.status(204).end());
// 6. API Routes
app.get('/api/todos', async (req, res) => {
try {
const [rows] = await pool.query('SELECT * FROM todos');
res.json(rows);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// POST: Add a new todo
app.post('/api/todos', async (req, res) => {
console.log("Received Add Request:", req.body);
const { title, desc, active } = req.body;
const sno = Date.now(); // Unique ID for MySQL BIGINT
try {
await pool.query(
'INSERT INTO todos (sno, title, `desc`, active) VALUES (?, ?, ?, ?)',
[sno, title, desc, active ? 1 : 0]
);
res.status(201).json({ sno, title, desc, active });
} catch (err) {
console.error("MySQL Insert Error:", err);
res.status(500).json({ error: err.message });
}
});
// PUT: Update todo status (Toggle)
app.put('/api/todos/:sno', async (req, res) => {
const { sno } = req.params;
const { active } = req.body;
try {
await pool.query('UPDATE todos SET active = ? WHERE sno = ?', [active ? 1 : 0, sno]);
res.json({ message: "Status updated" });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// DELETE: Remove a todo
app.delete('/api/todos/:sno', async (req, res) => {
const { sno } = req.params;
try {
await pool.query('DELETE FROM todos WHERE sno = ?', [sno]);
res.json({ message: "Todo deleted" });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
app.listen(3000, () => {
console.log('-----------------------------------------');
console.log('Server running on http://localhost:3000');
console.log('MySQL Connected & CSP Errors Resolved');
console.log('-----------------------------------------');
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,21 @@
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"dependencies": {
"body-parser": "^2.2.2",
"cors": "^2.8.5",
"express": "^5.2.1",
"helmet": "^8.1.0",
"mysql": "^2.18.1",
"mysql2": "^3.16.0"
}
}

13249
To do list har/todo-list/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
{
"name": "todo-list",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"bootstrap": "^5.3.8",
"jquery": "^3.7.1",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.3.17",
"@angular/cli": "^17.3.17",
"@angular/compiler-cli": "^17.3.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.4.2"
}
}

View File

@@ -0,0 +1,14 @@
<div class=" my-3">
<h3>Add a Todo</h3>
<form (ngSubmit)="onSubmit()">
<div class="mb-3">
<label for="Title" class="form-label">Todo Title</label>
<input type="text" [(ngModel)]="title" class="form-control" id="Title" name="Title" aria-describedby="emailHelp">
</div>
<div class="mb-3">
<label for="desc" class="form-label">Todo Description</label>
<input type="text" [(ngModel)]="desc" class="form-control" id="desc" name="desc">
</div>
<button type="submit" class="btn btn-primary">Add Todo</button>
</form>
</div>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AddTodoComponent } from './add-todo.component';
describe('AddTodoComponent', () => {
let component: AddTodoComponent;
let fixture: ComponentFixture<AddTodoComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AddTodoComponent]
})
.compileComponents();
fixture = TestBed.createComponent(AddTodoComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,26 @@
import { Component, EventEmitter, Output } from '@angular/core';
import { Todo } from '../../Todo';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-add-todo',
standalone: true,
imports: [FormsModule],
templateUrl: './add-todo.component.html',
styleUrl: './add-todo.component.css'
})
export class AddTodoComponent {
title: string = "";
desc: string = "";
@Output() todoAdd: EventEmitter<Todo> = new EventEmitter();
onSubmit() {
const todo = {
sno: 0,
title: this.title,
desc: this.desc,
active: true
}
this.todoAdd.emit(todo);
}
}

View File

@@ -0,0 +1,3 @@
.strike{
text-decoration: line-through;
}

View File

@@ -0,0 +1,9 @@
<div class="my3">
<h5 [ngClass]="{'strike': !todo.active}">{{todo.title}}</h5>
<p [ngClass]="{'strike': !todo.active}">{{todo.desc}}</p>
<div class="mb-3 form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1" (click)="onCheckboxClick(todo)" [checked]="!todo.active">
<label class="form-check-label" for="todo{{i}}">Done</label>
</div>
<button class="btn btn-danger" (click)="onClick(todo)">Delete</button>
</div>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TodoItemComponent } from './todo-item.component';
describe('TodoItemComponent', () => {
let component: TodoItemComponent;
let fixture: ComponentFixture<TodoItemComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [TodoItemComponent]
})
.compileComponents();
fixture = TestBed.createComponent(TodoItemComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,25 @@
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { Todo } from '../../Todo';
import { NgClass } from "@angular/common";
@Component({
selector: 'app-todo-item',
standalone: true,
imports: [NgClass],
templateUrl: './todo-item.component.html',
styleUrl: './todo-item.component.css'
})
export class TodoItemComponent {
@Input() todo!: Todo;
@Input() i!: number;
@Output() todoDelete: EventEmitter<Todo> = new EventEmitter();
@Output() todoCheckbox: EventEmitter<Todo> = new EventEmitter();
onClick(todo: Todo) {
console.log("onClick has been triggered");
this.todoDelete.emit(todo);
}
onCheckboxClick(todo: Todo) {
this.todoCheckbox.emit(todo);
}
}

View File

@@ -0,0 +1,11 @@
<div class="container">
<h1 class="text-center">Todo List by Harshit</h1>
<app-add-todo (todoAdd)="addTodo($event)"></app-add-todo>
<h3>Your Todos</h3>
<div *ngIf="this.todos.length===0; else elseBlock">No Todos to Display</div>
<ng-template #elseBlock>
<div *ngFor="let todo of todos; index as i">
<app-todo-item [todo]="todo" [i]="i" (todoDelete)="deleteTodo($event)" (todoCheckbox)="ToggleTodo($event)"></app-todo-item>
</div>
</ng-template>
</div>

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TodosComponent } from './todos.component';
describe('TodosComponent', () => {
let component: TodosComponent;
let fixture: ComponentFixture<TodosComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [TodosComponent]
})
.compileComponents();
fixture = TestBed.createComponent(TodosComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,63 @@
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { Todo } from '../../Todo';
import { TodoItemComponent } from "../todo-item/todo-item.component";
import { AddTodoComponent } from "../add-todo/add-todo.component";
@Component({
selector: 'app-todos',
standalone: true,
imports: [CommonModule, TodoItemComponent, AddTodoComponent],
templateUrl: './todos.component.html',
styleUrl: './todos.component.css'
})
export class TodosComponent implements OnInit {
todos: Todo[] = [];
private apiUrl = 'http://localhost:3000/api/todos';
constructor(private http: HttpClient) { }
ngOnInit() {
this.loadTodos();
}
loadTodos() {
this.http.get<Todo[]>(this.apiUrl).subscribe(data => {
this.todos = data;
});
}
addTodo(todo: Todo) {
// 1. Log to see if the function is even being called
console.log("Adding todo:", todo);
this.http.post<Todo>(this.apiUrl, todo).subscribe({
next: (newTodo) => {
console.log("Server saved it!", newTodo);
// 2. Add to the local list so it shows up immediately
this.todos.push(newTodo);
},
error: (err) => {
console.error("Failed to save to server", err);
}
});
}
deleteTodo(todo: Todo) {
this.http.delete(`${this.apiUrl}/${todo.sno}`).subscribe(() => {
const index = this.todos.indexOf(todo);
this.todos.splice(index, 1);
console.log("Deleted from server");
});
}
ToggleTodo(todo: Todo) {
const updatedTodo = { ...todo, active: !todo.active };
this.http.put<Todo>(`${this.apiUrl}/${todo.sno}`, updatedTodo).subscribe(response => {
const index = this.todos.indexOf(todo);
this.todos[index].active = !this.todos[index].active;
console.log("Status toggled on server");
});
}
}

View File

@@ -0,0 +1,6 @@
export class Todo {
sno: number = 0
title: string = ""
desc: string = ""
active: boolean = false
}

View File

@@ -0,0 +1,3 @@
<div class="container">
<app-todos></app-todos>
</div>

View File

@@ -0,0 +1,29 @@
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have the 'todo-list' title`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('todo-list');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('Hello, todo-list');
});
});

View File

@@ -0,0 +1,14 @@
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { TodosComponent } from "./MyComponents/todos/todos.component";
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, TodosComponent],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'todo-list';
}

View File

@@ -0,0 +1,11 @@
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes), // Handles your navigation
provideHttpClient() // Allows communication with your Node.js server
]
};

View File

@@ -0,0 +1,3 @@
import { Routes } from '@angular/router';
export const routes: Routes = [];

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>TodoList</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>

View File

@@ -0,0 +1,6 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));

View File

@@ -0,0 +1 @@
/* You can add global styles to this file, and also import other style files */

View File

@@ -0,0 +1,14 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts"
],
"include": [
"src/**/*.d.ts"
]
}

View File

@@ -0,0 +1,32 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"esModuleInterop": true,
"sourceMap": true,
"declaration": false,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "ES2022",
"module": "ES2022",
"useDefineForClassFields": false,
"lib": [
"ES2022",
"dom"
]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}

View File

@@ -0,0 +1,14 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
},
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}