Add SQLite database to backend, interacting with the frontend

This commit is contained in:
2024-09-04 16:42:37 +02:00
parent 8af11151d3
commit 7338bb216a
14 changed files with 1892 additions and 28 deletions

View File

@@ -0,0 +1,26 @@
import { Sequelize } from "sequelize-typescript"
// Models
import { Categories } from "./models/categories.model"
const dbName = "database"
const dbUser = "root"
const dbPassword = "123456"
// Definition of the database
export const sequelize = new Sequelize({
database: dbName,
dialect: "sqlite",
username: dbUser,
password: dbPassword,
storage: "database.sqlite",
models: [ Categories ]
})
export function startDatabase() {
// Create database and tables
sequelize.sync({ force: false })
.then(() => {
console.log(`Database & tables created!`)
})
}

View File

@@ -0,0 +1,7 @@
import { Table, Column, Model, PrimaryKey, AutoIncrement } from 'sequelize-typescript';
@Table
export class Categories extends Model {
@Column
name: string
}

View File

@@ -0,0 +1,7 @@
import { Request, Response, NextFunction, Router } from 'express'
export const api = Router()
api.get("/", (req: Request, res: Response, next: NextFunction) => {
res.send("Hello World!")
})

View File

@@ -0,0 +1,20 @@
import { Router, Request, Response, NextFunction } from "express";
import { Categories } from "../models/categories.model";
export const categories = Router()
categories.get("/", (req: Request, res: Response, next: NextFunction) => {
Categories.findAll()
.then(categories => res.json(categories))
.catch(next)
})
categories.post("/", (req: Request, res: Response, next: NextFunction) => {
try {
console.log(req.body)
const category = Categories.create(req.body)
res.status(201).json(category)
} catch (e) {
next(e)
}
})

View File

@@ -1,11 +0,0 @@
import express, { Request, Response, NextFunction } from 'express'
export const routes = app => {
var router = express.Router()
router.get("/", (req: Request, res: Response, next: NextFunction) => {
res.send("Hello World from the backend!")
})
app.use("/api/", router)
}

View File

@@ -1,7 +1,9 @@
import express from 'express'
import cors from 'cors'
import bodyParser from 'body-parser'
import { routes } from './routes/routes'
import { api } from './routes/api.routes'
import { categories } from './routes/categories.routes'
import { startDatabase } from './database'
const app = express()
const port = 3000
@@ -12,8 +14,12 @@ app.use(cors())
// Process JSON parameter
app.use(bodyParser.json())
// Use the app routes
routes(app)
// Create database and tables
startDatabase()
// Routes
app.use("/api", api)
app.use("/categories", categories)
// Start server
app.listen(port, () => {