159 lines
4.5 KiB
JavaScript
159 lines
4.5 KiB
JavaScript
import express from 'express';
|
|
import color from 'chalk';
|
|
import cors from 'cors';
|
|
import dotenv from 'dotenv';
|
|
|
|
dotenv.config(); // Sensible Konfigurationsvariablen in .env Datei auslagern
|
|
|
|
// Model
|
|
import ProductModel from './model/ProductModel.js'; // Dateiendung nicht vergessen
|
|
|
|
const PORT = process.env.SERVER_PORT; // || 8000;
|
|
const HOST = process.env.SERVER_HOST; // || '127.0.0.1'; // 'localhost'
|
|
const BASE_URL = `http://${HOST}:${PORT}`;
|
|
|
|
const app = express();
|
|
const products = ProductModel();
|
|
|
|
const corsOptions = {
|
|
origin: ['http://localhost:3000', 'http://127.0.0.1:3000'],
|
|
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
|
|
};
|
|
|
|
// lade Produkte
|
|
products.load();
|
|
|
|
// Middleware
|
|
app.use(cors(corsOptions)); // Fängt alle HTTP-Requests vor den Routenabfragen ab.
|
|
app.use(express.json()); // HTTP-Request Body wird als JSON Objekt erwartet und geparsed wird. // app.use(bodyParser.json()) - Modul body-parser war in express 4 notwendig
|
|
|
|
app.use((req, res, next) => {
|
|
console.log(color.yellow('HTTP-Method: '), color.magenta(req.method));
|
|
next();
|
|
});
|
|
|
|
// Routes
|
|
app.get('/', (req, res) => {
|
|
// console.log(req.headers);
|
|
|
|
res.send('SERVER WORKS!'); // HTTP-Response wird gesendet.
|
|
});
|
|
|
|
app.get('/persons', (req, res) => {
|
|
// res.setHeader('Content-Type', 'application/json'); // nicht notwendig den Content-Type selber zu definieren, da das express automatisch zuweist.
|
|
|
|
const persons = [
|
|
{ firstName: 'John', lastName: 'Wick' },
|
|
{ firstName: 'Jane', lastName: 'Doe' },
|
|
{ firstName: 'Max', lastName: 'Mustermann' },
|
|
];
|
|
// res.send(JSON.stringify(persons)); // nicht notwendig JS Objekte in JSON Strings umzuwandeln, das das express automatisch umwandelt
|
|
|
|
res.send(persons);
|
|
});
|
|
|
|
// REST API ======
|
|
// Representational State Transfer (abgekürzt REST)
|
|
// GET - Daten Holen
|
|
// POST - Daten hinzufügen
|
|
// PUT/PATCH - Daten aktualisieren / Einen Datensatz aktualisieren
|
|
// DELETE - Daten löschen
|
|
|
|
// HTTP - Methode - POST
|
|
// (C)RUD - create - neues Produkt erstellen
|
|
// BRE(A)D - add
|
|
app.post('/api/products', (req, res) => {
|
|
const product = req.body;
|
|
|
|
if (!products.add(product)) {
|
|
return res.status(400).send({ msg: 'Could not add product', status: 400, success: false });
|
|
}
|
|
|
|
return res.send({ msg: 'Product added', status: 200, success: true, data: product });
|
|
});
|
|
|
|
// HTTP - Methode - GET
|
|
// C(R)UD - read
|
|
// (B)READ - browse
|
|
app.get('/api/products', (req, res) => {
|
|
const data = products.getAll();
|
|
return res.send(data);
|
|
});
|
|
|
|
// HTTP - Methode - GET
|
|
// C(R)UD - read
|
|
// B(R)EAD - read
|
|
app.get('/api/products/:id', (req, res) => {
|
|
const id = req.params.id; // routenparameter :id wird als Eigenschaft in params-Objekt abgelegt
|
|
const product = products.get(id);
|
|
|
|
if (!product) {
|
|
return res.status(400).send({ msg: 'Could not get product', status: 400, success: false });
|
|
}
|
|
|
|
return res.send(product);
|
|
});
|
|
|
|
// HTTP - Methode - PUT/PATCH
|
|
// CR(U)D - update
|
|
// BR(E)AD - edit
|
|
app.put('/api/products', (req, res) => {
|
|
const product = req.body;
|
|
|
|
const updated = products.update(product);
|
|
|
|
if (!updated) {
|
|
return res.status(400).send({ msg: 'Could not update product', status: 400, success: false });
|
|
}
|
|
|
|
return res.send({ msg: 'Product updated', status: 200, success: true, data: product });
|
|
});
|
|
|
|
// HTTP - Methode - PATCH
|
|
// reseten von Produkten
|
|
app.patch('/api/products/reset', (req, res) => {
|
|
const reset = req.body.reset;
|
|
|
|
if (!reset) {
|
|
return res.status(400).send({ msg: 'Could not reset products', status: 400, success: false });
|
|
}
|
|
|
|
products.reset();
|
|
|
|
return res.send({ msg: 'Products reseted', status: 200, success: true, data: reset });
|
|
});
|
|
|
|
// HTTP - Methode - PATCH
|
|
// speichern von Produkten
|
|
app.patch('/api/products/save', (req, res) => {
|
|
const save = req.body.save;
|
|
|
|
if (!save) {
|
|
return res.status(400).send({ msg: 'Could not save products', status: 400, success: false });
|
|
}
|
|
|
|
products.save();
|
|
|
|
return res.send({ msg: 'Products saved', status: 200, success: true, data: save });
|
|
});
|
|
|
|
// HTTP - Methode - DELETE
|
|
// CRU(D) - delete
|
|
// BREA(D) - delete
|
|
app.delete('/api/products/:id', (req, res) => {
|
|
const id = req.params.id;
|
|
|
|
if (!products.delete(id)) {
|
|
return res.status(400).send({ msg: 'Could not delete product', status: 400, success: false });
|
|
}
|
|
|
|
return res.send({ msg: 'Product deleted', status: 200, success: true, data: id });
|
|
});
|
|
|
|
// =========
|
|
|
|
app.listen(PORT, HOST, () => {
|
|
console.log(color.magenta(`🚀 Server is running at: ${BASE_URL}`));
|
|
console.log(color.yellow('CTRL + C to close.'));
|
|
});
|